The easiest QT TCP server

What do I need to receive data from a client?

QTcpServer Server; if(!Server.listen("127.0.0.1", 9000)) { return; } connect(Server, SIGNAL(newConnection()), this, SLOT(ReceiveData())); 

How correct is this? What do I need in ReceiveData? Do I really need another function to get the data? I would like to save it in a QByteArray

thanks

+4
source share
2 answers

You saw this example:

http://doc.qt.io/qt-5/qtnetwork-fortuneserver-server-cpp.html

PS: Yes, you need at least one callback function:

1) accept new connections

2) Receive and send data on the connection (s)

+3
source

Since this has not been answered, here is a really basic example.

In your ReceiveData slot, you will need to accept a connection to the server.

In Qt, QTcpServer does this by calling nextPendingConnection ().

That way, the newConnection QTcpServer slot will call your ReceiveData slot.

In your gotata slot, you can do something like:

 void ReceiveData() { QTcpSocket *socket = server->nextPendingConnection(); if (!socket) return; qDebug("Client connected"); socket->waitForReadyRead(5000); QByteArray data = socket->readAll(); qDebug(data.constData()); socket->close(); } 

Note. This is an example of a lock, waitForReadyRead will hang in the stream for up to 5000 milliseconds.

To make a non-blocking example, you need to connect another slot to the new connection ready signal.

+1
source

All Articles