如何读取QTcpSocket中的完整数据? [英] How to read complete data in QTcpSocket?

查看:2119
本文介绍了如何读取QTcpSocket中的完整数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在服务器(用java实现)会向我发送一些流数据,我的代码如下:

Now the server (implemented with java) will send some stream data to me, my code is like below:

connect(socket, SIGNAL(readyRead()), this, SLOT(read_from_server()));



in the read_from_server():

{
    while (socket->bytesAvailable())
    {
        QString temp = socket->readAll();
    }
}

但我发现即使服务器发送一个字符串只有几个字符,数据被截断,我的函数被调用两次,因此 temp 是我不想要的完整数据。

如果服务器给我一个更长的字符串,我的功能可能被调用三次或更多次,使我不知道在什么时候数据被完全转移。

所以任何人都可以告诉我如何完全接收数据,没有这么多的步骤麻烦?对不起,如果这是重复的一些问题,别人,我不能得到他们的答案为我工作。非常感谢!

but I find that even the server sent me a string with only several characters, the data is truncated, and my function is called twice, thus temp is the never complete data that I want.
If server send me a longer string, my function may be called three or more times, making me diffficult to know at which time the data is transfered completely.
So anyone can tell me how to completely receive the data easily, without so many steps of bothering? I'm sorry if this is duplicated with some questions else, I couldn't get their answers work for me. Many thanks!

推荐答案

您看到的是客户端 - 服务器通信的正常现象。数据以包的形式发送,readyRead信号通知您的程序有可用的数据,但没有什么或有多少数据的概念,因此您必须处理这个。

What you're seeing is normal for client-server communication. Data is sent in packets and the readyRead signal is informing your program that there is data available, but has no concept of what or how much data there is, so you have to handle this.

要正确读取数据,您需要一个缓冲区(如@ratchetfreak所述),以便在从流中读取字节时附加字节。重要的是,您知道正在发送的数据的格式,以便知道您何时有完整的消息。我之前使用了至少两种方法: -

To read the data correctly, you will need a buffer, as mentioned by @ratchetfreak, to append the bytes as they're read from the stream. It is important that you know the format of the data being sent, in order to know when you have a complete message. I have previously used at least two methods to do this: -

1)确保发送的消息以发送消息的大小(字节)开头。在接收数据时,您首先读取大小并保持附加到缓冲区,直到它达到预期大小为止。

1) Ensure that sent messages begin with the size, in bytes, of the message being sent. On receiving data, you start by reading the size and keep appending to your buffer until it totals the size to expect.

2)以已知格式发送所有数据,例如作为 JSON XML ,可以检查消息的结束。例如,在JSON的情况下,所有数据包将以大括号{开头并以结尾括号'}结尾,因此您可以计算大括号并匹配数据,或使用QJsonDocument :: fromRawData验证数据已完成。

2) Send all data in a known format, such as JSON or XML, which can be checked for the end of the message. For example, in the case of JSON, all packets will begin with an opening brace '{' and end with a closing brace '}', so you could count braces and match up the data, or use QJsonDocument::fromRawData to verify that the data is complete.

使用这两种方法后,我建议使用第一个;包括要发送的邮件的大小。

Having used both of these methods, I recommend using the first; include the size of a message that is being sent.

这篇关于如何读取QTcpSocket中的完整数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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