Example of a basic Qt TCP server¶
#include <QTcpServer>
#include <QTcpSocket>
#include <QDebug>
class MyTcpServer : public QObject
{
Q_OBJECT
public:
explicit MyTcpServer(QObject *parent = nullptr) : QObject(parent)
{
mTcpServer = new QTcpServer(this);
connect(mTcpServer, &QTcpServer::newConnection, this, &MyTcpServer::onNewConnection);
if (!mTcpServer->listen(QHostAddress::Any, 6000)) {
qDebug() << "Server could not be started!";
} else {
qDebug() << "Server started on port 6000!";
}
}
private slots:
void onNewConnection()
{
QTcpSocket *clientSocket = mTcpServer->nextPendingConnection();
qDebug() << "New client connected:" << clientSocket->peerAddress().toString();
connect(clientSocket, &QTcpSocket::readyRead, this, &MyTcpServer::onReadyRead);
connect(clientSocket, &QTcpSocket::disconnected, this, &MyTcpServer::onClientDisconnected);
clientSocket->write("Welcome to the Qt TCP server!\r\n");
}
void onReadyRead()
{
QTcpSocket *clientSocket = qobject_cast<QTcpSocket*>(sender());
if (clientSocket) {
QByteArray data = clientSocket->readAll();
qDebug() << "Received from client:" << data;
clientSocket->write("Echo: " + data); // Echo back the received data
}
}
void onClientDisconnected()
{
QTcpSocket *clientSocket = qobject_cast<QTcpSocket*>(sender());
if (clientSocket) {
qDebug() << "Client disconnected:" << clientSocket->peerAddress().toString();
clientSocket->deleteLater(); // Clean up the socket object
}
}
private:
QTcpServer *mTcpServer;
};