使用 QTcpSocket 的 Tcp 数据包 [英] Tcp packets using QTcpSocket

查看:42
本文介绍了使用 QTcpSocket 的 Tcp 数据包的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道 TCP 保证所有数据包都会到达.但是一个数据包可以分成2个或更多吗?我正在使用 Qt 和 QTcpSocket 类,我想知道 ReadyRead() 信号是否仅在完整数据包到达时发出.或者换句话说,以第一个字节发送数据包大小然后循环等待直到所有字节都到达有什么意义吗?或者我可以只调用 socket->readAll() 并且我必须得到一个完整的数据包?

I know that TCP guarantees that all packets will arrive. But can a packet be separated into 2 or more? I am using Qt with class QTcpSocket, and I want to know is ReadyRead() signal is emitted only when full packet arrives. Or in other words, is there any sense to send packet size in first bytes and then wait in loop until all bytes had arrived? Or I can just call socket->readAll() and I must get one full packet?

推荐答案

如果发送大量数据,数据包可以分开到达.或者,可以在一个 readyRead 槽中接收多条消息.

If a large amount of data is sent, the packet can arrive in separate parts. Alternatively, multiple messages can be received in one readyRead slot.

通过将第一个字节设置为将要发送的字节数来控制这一点是一种很好的做法.然后,在 readyRead 中,您读取第一个字节并将数据附加到缓冲区,直到接收到预期的数据量.

It's good practice to control this by setting the first byte(s) to the number of bytes that will be sent. Then, in readyRead, you read the first bytes and append the data to a buffer until the expected amount of data has been received.

在接收数据时,这也意味着如果在一次调用 readyRead() 中收到多条消息,您可以知道第一条消息在哪里结束,下一条消息从哪里开始.

In receiving data, this also means that if multiple messages are received in one call to readyRead(), you can know where the first message ends and the next one begins.

这是一个在readyRead函数()中接收数据的客户端的例子

Here's an example of a client that receives data in a readyRead function()

void MyClass::readyRead()
{
    // m_pConnection is a QTcpSocket

    while(m_pConnection->bytesAvailable())
    {
        QByteArray buffer;

        int dataSize;
        m_pConnection->read((char*)&dataSize, sizeof(int));
        buffer = m_pConnection->read(dataSize);

        while(buffer.size() < dataSize) // only part of the message has been received
        {
            m_pConnection->waitForReadyRead(); // alternatively, store the buffer and wait for the next readyRead()
            buffer.append(m_pConnection->read(dataSize - buffer.size())); // append the remaining bytes of the message
        }

        QString msg(buffer); // data in this case is JSON, so we can use a QString
        emit Log(QString("\tMessage Received: %1").arg(msg));

        // Do something with the message
        ProcessMessage(msg);
    }
}

这篇关于使用 QTcpSocket 的 Tcp 数据包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆