I've been attempting to write a client/server app with boost now, so far it sends and receives but I can't seem to just read X bytes into a vector.
If I use the following code
vector<uint8_t> buf;
for (;;)
{
buf.resize(4);
boost::system::error_code error;
size_t len = socket.read_some(boost::asio::buffer(buf), error);
if (error == boost::asio::error:开发者_StackOverflow社区:eof)
break; // Connection closed cleanly by peer.
else if (error)
throw boost::system::system_error(error); // Some other error.
}
And the packet is bigger then 4 bytes then it seems it keeps writing into those 4 bytes until the entire packet has been received, however I want it to fetch 4 bytes, then allow me to parse them, and then get the rest of the packet.
Can anyone provide me with a working example, or at least a pointer on how to make it work properly ?
Regards, Xeross
You say that the socket has more than 4 bytes available to read, in which case your code is correctly continuously looping since an eof won't be encountered until all the data is read. It seems to me that you want to use read() rather than read_some() since the latter might return with less than the four bytes you want. From the read_some documentation.
The read_some operation may not read all of the requested number of bytes. Consider using the read function if you need to ensure that the requested amount of data is read before the blocking operation completes.
You need to read the first 4 bytes (using read), process them (you don't need to be in a loop to do this), and then do a looping read and process the data until you get an error condition or eof.
I think you want more like that below:
vector<uint8_t> buf(4);
try
{
size_t len = read(socket, boost::asio::buffer(buf));
assert(len == 4);
// process the 4 bytes in buf
}
catch (boost::system::system_error &err)
{
// handle the error e.g by returning early
}
boost::system::error_code error;
while (!error)
{
size_t len = socket.read_some(boost::asio::buffer(buf), error);
// process len bytes
}
精彩评论