Creating TCP Server

In this section, we will learn how to create a TCP server that constantly listens to a specific port for incoming messages. For the sake of simplicity, we will just create a global chat room in which every user can see the messages sent by each and every user within the chat room, instead of a one-to-one messaging system with a friend list. You can easily improvise this system to the latter once you have understood how a chat system functions.

First, go to File | New File or Project and choose C++ Class under the C++ category. Then, name the class as server and select QObject as the base class. Make sure the Include QObject option is ticked before proceeding to create the custom class. You should have also noticed the absence of mainwindow.ui, mainwindow.h, and mainwindow.cpp. This is because there is no user interface in a console application project.

Once the server class has been created, let's open up server.h and add in the following headers, variables and functions:

#ifndef SERVER_H 
#define SERVER_H 
 
#include <QObject> 
#include <QTcpServer> 
#include <QTcpSocket> 
#include <QDebug> 
#include <QVector> 
 
private: 
   QTcpServer* chatServer; 
   QVector<QTcpSocket*>* allClients; 

public:
explicit server(QObject *parent = nullptr);
void startServer();
void sendMessageToClients(QString message);

public slots:
void newClientConnection();
void socketDisconnected();
void socketReadyRead();
void socketStateChanged(QAbstractSocket::SocketState state);

Next, create a function called startServer() and add the following code to the function definition in server.cpp:

void server::startServer() 
{ 
   allClients = new QVector<QTcpSocket*>; 
 
   chatServer = new QTcpServer(); 
   chatServer->setMaxPendingConnections(10); 
   connect(chatServer, SIGNAL(newConnection()), this, 
SLOT(newClientConnection())); if (chatServer->listen(QHostAddress::Any, 8001)) { qDebug() << "Server has started. Listening to port 8001."; } else { qDebug() << "Server failed to start. Error: " + chatServer-
>errorString(); } }

We created a QTcpServer object called chatServer and made it constantly listen to port 8001. You can choose any unused port number ranging from 1024 to 49151. Other numbers outside of this range are usually reserved for common systems, such as HTTP or FTP services, so we better not use them to avoid conflicts. We also created a QVector array called allClients to store all the connected clients so that we can make use of it later to redirect incoming messages to all users.

We also used the setMaxPendingConnections() function to limit the maximum pending connections to 10 clients. You can use this method to keep the number of active clients to a specific amount so that your server's bandwidth is always within its limit. This can ensure good service quality and maintain a positive user experience.