Created
April 29, 2020 08:43
-
-
Save alvaro893/d79ef7eae82ba4684a147066b8d06cc1 to your computer and use it in GitHub Desktop.
TCP communication in QT
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <QObject> | |
#include <QTcpServer> | |
#include <QTcpSocket> | |
/* | |
Tcp socket communication example | |
Note: the signal writeToSocket is used to write into the last opened socket | |
**/ | |
class TcpCommunication : public QObject | |
{ | |
Q_OBJECT | |
public: | |
explicit TcpCommunication(QObject *parent = nullptr); | |
private slots: | |
void onError(QAbstractSocket::SocketError socketError); | |
void onNewConnection(); | |
private: | |
QTcpServer *server; | |
signals: | |
void writeToSocket(const QByteArray &ba); | |
}; | |
TcpCommunication::TcpCommunication(QObject *parent) : QObject(parent) | |
{ | |
server = new QTcpServer(this); | |
connect(server, &QTcpServer::newConnection, this, &TcpCommunication::onNewConnection); | |
connect(server, &QTcpServer::acceptError, this, &TcpCommunication::onError); | |
bool status = server->listen(QHostAddress::LocalHost, 54932); | |
if(status){ | |
qInfo() << "TCP server listening on" | |
<< server->serverAddress().toString() << ":" << server->serverPort(); | |
}else{ | |
qWarning() << "Error, couldn't start TCP server"; | |
} | |
} | |
void TcpCommunication::onError(QAbstractSocket::SocketError socketError) | |
{ | |
qDebug() << "Socket Error:" << socketError; | |
} | |
void TcpCommunication::onNewConnection() | |
{ | |
QTcpSocket *socket = server->nextPendingConnection(); | |
connect(socket, &QTcpSocket::readyRead, [=](){ | |
qDebug() << "received from TCP:" << socket->read(1000); | |
socket->write("ok"); | |
}); | |
connect(socket, &QTcpSocket::disconnected, [=]{ | |
qInfo() << "closing socket peer port: " << socket->peerPort(); | |
socket->deleteLater(); | |
}); | |
connect(this, &TcpCommunication::writeToSocket, [=](const QByteArray &data){ | |
if(socket->isOpen() && socket->isWritable()) | |
socket->write(data); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment