【发布时间】:2016-03-15 09:44:46
【问题描述】:
您好,我正在尝试在 poco 中编写 TCP 连接。客户端发送带有此字段的数据包:
packetSize : int
date : int
ID : int
所以前 4 个字节包含数据包大小。在接收端我有这个代码:
int packetSize = 0;
char *bufferHeader = new char[4];
// receive 4 bytes that contains packetsize here
socket().receiveBytes(bufferHeader, sizeof(bufferHeader), MSG_WAITALL);
Poco::MemoryInputStream *inStreamHeader = new Poco::MemoryInputStream(bufferHeader, sizeof(bufferHeader));
Poco::BinaryReader *BinaryReaderHeader = new Poco::BinaryReader(*inStreamHeader);
(*BinaryReaderHeader) >> packetSize; // now we have the full packet size
现在我正在尝试将所有剩余的传入字节存储到一个数组中以供将来二进制读取:
int ID = 0;
int date = 0;
int availableBytes = 0;
int readedBytes = 0;
char *body = new char[packetSize - 4];
do
{
char *bytes = new char[packetSize - 4];
availableBytes = socket().receiveBytes(bytes, sizeof(bytes), MSG_WAITALL);
if (availableBytes == 0)
break;
memcpy(body + readedBytes, bytes, availableBytes);
readedBytes += availableBytes;
} while (availableBytes > 0);
Poco::MemoryInputStream *inStream = new Poco::MemoryInputStream(body, sizeof(body));
Poco::BinaryReader *BinaryReader = new Poco::BinaryReader(*inStream);
(*BinaryReader) >> date;
(*BinaryReader) >> ID;
cout << "date :" << date << endl;
cout << "ID :" << ID << endl;
问题是 body 的字节块没有存储剩余的字节,它总是只有前 4 个字节(日期)。所以在输出中日期是正确的,但 ID 与预期不符。我尝试在没有块复制的情况下对其进行流式传输,并在没有循环的情况下手动接收每个字段,这很好并且有预期的数据。但是当我尝试将传入的字节存储到一个数组中,然后将该数组传递给内存流来读取它时,我只有第一个块是正确的和预期的!!
我真的需要将所有传入的字节存储到一个数组中,然后读取整个数组,我应该如何更改我的代码?
非常感谢
【问题讨论】:
标签: c++ sockets poco-libraries