我根据this post编写了我的QTcpServer。套接字在前4个字节(qint32)上插入QByteArray的总字节数。一切都很好
服务器
static inline QByteArray IntToArray(qint32 source);
QByteArray IntToArray(qint32 source) {
QByteArray temp;
QDataStream data(&temp, QIODevice::ReadWrite);
data << source;
return temp;
}
void multisocket::write_socket(const QJsonObject &obj){
QJsonDocument doc(obj);
QByteArray array(doc.toJson());
qint32 size = array.size();
qDebug() << "sending..." << size << array.size();
QByteArray total = IntToArray(size);
socket->write(total);
socket->write(array);
qDebug() << socket->waitForBytesWritten();
}
服务器输出:
write_socket sending... 22299 22299
write_socket true
客户端:
在客户端上,我进行循环并验证总大小。继续接收直到 总到了:
static inline qint32 ArrayToInt(QByteArray source);
void network_controller::read_all_buffer(){
QByteArray buffer;
qint32 size = 0;
while (s->bytesAvailable() > 0)
{
buffer.append(s->readAll());
while ((size == 0 && buffer.size() >= 4) ||
(size > 0 && buffer.size() >= size)){
if (size == 0 && buffer.size() >= 4)
{
size = ArrayToInt(buffer.mid(0, 4));
buffer.remove(0, 4);
}
if (size > 0 && buffer.size() >= size)
{
QByteArray data = buffer.mid(0, size);
QJsonObject obj = socket_ba_to_json(data);
emit network_callback(obj);
}
}
}
}
问题:在客户端上,第一个字节的大小似乎没问题。我从服务器和客户端收到22299,但循环没有停止,缓冲区大小增加。我错过了什么?
客户输出:
read_all_buffer Receiving: 22299 1460
read_all_buffer Receiving: 538976288 8760
read_all_buffer Receiving: 538976288 4380
read_all_buffer Receiving: 808192544 1460
read_all_buffer Receiving: 538976288 2920
read_all_buffer Receiving: 1381979713 3323
答案 0 :(得分:1)
解决方案:
显然是关于范围的事情。将大小和缓冲区移动到标题并在数据完成后清除可以解决问题。
标题:
private:
void write_socket(QJsonObject obj);
QByteArray buffer;
qint32 size;
来源:
void network_controller::read_all_buffer()
{
while (s->bytesAvailable() > 0)
{
buffer.append(s->readAll());
while ((size == 0 && buffer.size() >= 4) ||
(size > 0 && buffer.size() >= size))
{
if (size == 0 && buffer.size() >= 4)
{
size = ArrayToInt(buffer.mid(0, 4));
buffer.remove(0, 4);
}
if (size > 0 && buffer.size() >= size)
{
QByteArray data = buffer.mid(0, size);
QJsonObject obj = socket_ba_to_json(data);
size = 0;
buffer = QByteArray();
emit network_callback(obj);
}
}
}
}
答案 1 :(得分:0)
对于服务器的一个答案,似乎多次调用 read_all_buffer 。尝试将 buffer 和 size 移动到 network_controller 的字段中,并在发出 network_callback 后清除它。