问题描述
我正在接收一个字节流,我需要拆分消息,例如
I'm receiving a stream of bytes and i need to split out messages, for example
Message1\nMessage2\nMessage3\nMess
每条消息都将附加 '\n' 字符,但是当一个完整的消息无法放入缓冲区时,它会在下一次 recv
调用中获取消息的一部分和另一部分,这可能需要重新分配内存附加消息.
Each message will be appended by '\n' character but when a complete message cannot fit into buffer it gets a part of message and another part of it on next recv
call which might require memory reallocations to append the message.
我这样做正确还是有更好的方法来处理消息而不是重新分配缓冲区?
Am i doing this correctly or would there be any better way to handle the messages instead of reallocating buffer?
推荐答案
您可以在消息前面加上消息的长度,然后先阅读.然后分配一个足够大的缓冲区来接收内容,并接收直到读取所需的字节数.
You could prepend the length of your message to the message, and read that first. Then allocate a buffer big enough to recieve the contents, and recv until it's read the required number of bytes.
例如
int len = 0;
if(recv(socket, reinterpret_cast<char*>(&len), sizeof(int), 0) == sizeof(int))
{
std::vector<char> buffer;
buffer.resize(len);
int bytesRead = 0;
while(bytesRead < len)
{
//read as much as we can. note: byteInc may not == len-bytesRead.
int byteInc = recv(socket, &buffer[bytesRead], len-bytesRead, 0);
if(byteInc != SOCKET_ERROR)
{
bytesRead += byteInc;
}
else
{
//should probably handle this error properly
break;
}
}
//buffer now contains the complete message.
some_processing_function(buffer);
}
这篇关于TCP 客户端消息处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!