QTcpSocket read packet
-
Hello,
my application opens up a QTcpServer, waits for a connection and then retrieved a QTcpSocket from that attempted connection to retrieve incomming data. This all works, but now I am not sure on how to proceed from here.
{ . . . // Create tcp server for receiving packets // Connect to slot if data is available to read m_tcpServer = QSharedPointer<QTcpServer>(new QTcpServer(this)); connect(m_tcpServer.data(), &QTcpServer::newConnection, [&]() { // Retrieve client socket that tried to connect to tcp server m_tcpServerClient = QSharedPointer<QTcpSocket>( m_tcpServer.data()->nextPendingConnection()); // Connect readyRead of client socket to receive packets connect(m_tcpServerClient.data(), &QTcpSocket::readyRead, this, &MycClass::recEchoDataReady); emit echoConnected(); }); m_tcpServer.data()->listen(ip, port); } void UlgSimu::recEchoDataReady() { QByteArray data = m_tcpServerClient.data()->readAll(); transformDatagram(data); }
Does data contain the whole packet? Does it only contain the payload?
-
Hello,
my application opens up a QTcpServer, waits for a connection and then retrieved a QTcpSocket from that attempted connection to retrieve incomming data. This all works, but now I am not sure on how to proceed from here.
{ . . . // Create tcp server for receiving packets // Connect to slot if data is available to read m_tcpServer = QSharedPointer<QTcpServer>(new QTcpServer(this)); connect(m_tcpServer.data(), &QTcpServer::newConnection, [&]() { // Retrieve client socket that tried to connect to tcp server m_tcpServerClient = QSharedPointer<QTcpSocket>( m_tcpServer.data()->nextPendingConnection()); // Connect readyRead of client socket to receive packets connect(m_tcpServerClient.data(), &QTcpSocket::readyRead, this, &MycClass::recEchoDataReady); emit echoConnected(); }); m_tcpServer.data()->listen(ip, port); } void UlgSimu::recEchoDataReady() { QByteArray data = m_tcpServerClient.data()->readAll(); transformDatagram(data); }
Does data contain the whole packet? Does it only contain the payload?
@Redman
You should not be talking about (or creating variables) for "packets", "payloads" or "datagrams" here. All you know is thatQTcpSocket::readyRead
signal will fire when 1 or more data bytes arrive at socket. That's it! It could be any number from 1 to the total number of data bytes (as returned byreadAll()
orbytesAvailable()
) sent from the other side. And consequently it could be emitted any number of times with varying numbers of bytes. You should make no assumptions about how many will be available each time. If you need to "collect" a number of bytes to constitute some "message" your code expects to parse it is your job to buffer all the bytes received and work from that. -