我正在尝试使用Qt的长度先于TCP消息。我有以下方法:QT套接字读取丢失字节
QByteArray con::read()
{
QByteArray s;
s = _pSocket->read(4);
if (s.length() == 4) {
int size = char_to_int32(s);
s = _pSocket->read(size);
}
return s;
}
嗯,它不起作用。看起来我读完第4个字节后会丢失所有数据:第一次读取正常,但read(size)
不返回任何内容。有没有办法解决这个问题?
的char_to_int32是:
int char_to_int32(QByteArray s)
{
int size = 0;
size |= (s.at(0) << 24);
size |= (s.at(1) << 16);
size |= (s.at(2) << 8);
size |= (s.at(3));
return size;
}
编辑:
发送功能(纯C):
int send(int connfd, const unsigned char* message, unsigned int size) {
int c;
unsigned char* bytes = (unsigned char*) malloc(4 + size);
int32_to_char(size, bytes); // converts message size to 4 bytes
memcpy(bytes + 4, message, size);
c = write(connfd, bytes, 4 + size);
free(bytes);
if (c <= 0)
return -1;
else
return 0;
}
顺便说一句,当我打电话_pSocket-> readAll( ),读取整个数据包,包括4字节大小和消息本身。
编辑:
void int32_to_char(uint32_t in, char* bytes) {
bytes[0] = (in >> 24) & 0xFF;
bytes[1] = (in >> 16) & 0xFF;
bytes[2] = (in >> 8) & 0xFF;
bytes[3] = in & 0xFF;
return;
}
你能否提供'char_to_int32'函数定义? – mfontanini
大小是多少?你确定它是32位有符号的int吗? –
尝试在read()中使用它之前打印“大小”值。我敢打赌,问题在那里 – nax83