c++ - 通过 QDataStream 从客户端发送到服务器的字节不匹配

标签 c++ qt qtcpsocket

我正在尝试在 QTcpSocket 上发送一个 QByteArray 。我面临的问题是,虽然我发送了一个长度为 25 的数组,但在服务器上它收到了 59 个字节。这是我的示例代码:

//client
QDataStream out(qctcpSocket);
out<<qByteArray;  // qByteArray is of length 25
const int nbBytes = qctcpSocket->write(qByteArray); // nbBytes returbs 25 

//server
TArray<char> data;
uint32 pendingData = 0;
TArray<char> newData; // customized Template for Array
    newData.InsertZeroed(0, pendingData);
    int32 bytesRead = 0;
    rcvSocket->Recv(reinterpret_cast<uint8*>(newData.GetData()), pendingData, bytesRead);
    data += newData;//length is 59 !!

最佳答案

我在您的客户端代码中发现了两个问题。由于您使用(假设)连接的套接字作为数据流底层设备:

QDataStream out(qctcpSocket);

你正在通过套接字发送数据,使用这一行:

out<<qByteArray;  // qByteArray is of length 25

那么您将在下一个数据中发送更多数据:

const int nbBytes = qctcpSocket->write(qByteArray); // nbBytes returbs 25 

这是第一个问题:您正在尝试发送相同的数据两次。但是每次调用之间的数据不同(这是第二个问题):执行第一次发送,使用流,将在套接字上放置一个字节长的数组QByteArray::size + 4,四个流对象添加的额外字节(它是实际字节数组之前的大端 32 位整数,并以字节为单位保存其长度)。

相反,第二次发送仅将字节数组中的 25 个字节放在套接字上,我想这正是您首先想要的。

我的建议是完全摆脱数据流并使用 QTcpSocket 类的 write 方法,如果您不这样做,这应该是最好的选择在另一个端点(服务器)上使用 Qt。

如果你仍然想使用流,去掉发送端的write,并确保在接收端使用QDataStream对象,所以你必须:

//Build a QByteArray out of the incoming bytes:
QByteArray raw_data = ...

//Use it as the stream device
QDataStream stream(raw_data);

//Use another byte array to fetch the data out of the stream
QByteArray data;
stream >> data;

或者您可以手动去除前四个字节,我真的不推荐这样做。

关于c++ - 通过 QDataStream 从客户端发送到服务器的字节不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50443678/

相关文章:

c++ - 暂停执行直到收到套接字上的特定消息?

c++ - 为什么 push_back 进入 vector<vector<int>> 导致段错误?

c++ - 使用strtok分割字符串

c++ - Qt: undefined reference

python - QT QItemSelectionModel 忽略列?

c++ - Qt 错误 - 错误 : Not a signal or slot declaration

c++ - 尝试在 Visual Studio 2013 中创建 Web 服务器对象的新实例时抛出错误

c++ - 如何在 QtCreator (Linux Ubuntu) 中编译和运行一个随机的单个 C++ 文件?

QT QMatrix4x4 矩阵,用于原点 x 和 y 的缩放和旋转

c++ - Qt 断开连接后连接到服务器时客户端程序崩溃