WIP-How to create a simple chat application
Introduction
This article will illustrate a simple chat client and server communicating over TCP. The aim is to clarify aspects of QTcpSocket/QTcpServer that are not developed in the official Qt Fortune example. This has no intention to be a fully featured chat application.
You can find the source code relating to this example on GitHub
Pre-Requisites
An intermediate level of knowledge of Qt Familiarity with C++11 concepts, especially lambdas and std::bind
The Logic
This application will use a central server that will manage the communication among clients via JSON messages. We'll implement 2 versions of the server, one that runs in a single server and one that distributes the sockets among multiple threads.
The Client
The client in this example is a simple QtWidgets application, the ui is minimal, just a button to connect to the server, a list view to display the messages received, a line edit to type your messages and a button to send them.
The core of the functionality is in the ChatClient class.
class ChatClient : public QObject
{
Q_OBJECT
Q_DISABLE_COPY(ChatClient)
public:
explicit ChatClient(QObject *parent = nullptr);
public slots:
void connectToServer(const QHostAddress &address, quint16 port);
void login(const QString &userName);
void sendMessage(const QString &text);
void disconnectFromHost();
private slots:
void onReadyRead();
signals:
void connected();
void loggedIn();
void loginError(const QString &reason);
void disconnected();
void messageReceived(const QString &sender, const QString &text);
void error(QAbstractSocket::SocketError socketError);
void userJoined(const QString &username);
void userLeft(const QString &username);
private:
QTcpSocket *m_clientSocket;
bool m_loggedIn;
void jsonReceived(const QJsonObject &doc);
};
Let's break down what each of these methods and member does:
Private Members | m_clientSocket | The socket that will interact with the server |
---|---|---|
m_loggedIn | Used to record whether the client already agreed a username with the server or not | |
jsonReceived() | Method to process the messages received from the server | |
jsonReceived() | Example | |
Example | Example | |
Example | Example | |
Example | Example | |
Example | Example | |
Example | Example | |
Example | Example | |
Example | Example | |
Example | Example | |
Example | Example | |
Example | Example | |
Example | Example | |
Example | Example |