Lets say I have a Boos.Asio TCP client, that can send a string, like this:
client.sendStr("1111");
I also have a asynchronous Boost.Asio TCP server, that will handle incoming packets and print them, like this:
received string: "1111", size: 5.
Problem is, that when I call client.sendStr()
multiple times, like this
client.sendStr("1111");
client.sendStr("2222");
client.sendStr("3333");
I might get various results on the server side, for example:
received string: "1111", size: 5.
received string: "2222", size: 5.
received string: "2222", size: 5.
or
received string: "111122223333", size: 13.
or
received string: "11112222", size: 9.
received string: "3333", size: 5.
I am a networking newbie, but I guess that the reason for this situation is that TCP is a "stream based protocol".
My questions are:
1) Can I prevent Boost.Asio from doing this? (lets say "1111" and "2222" are control packets of my application, and I don't what them to be connected).
2) Is there a possibility that I will get callbacks like this:
received string: "111122", size: 7.
received string: "22333", size: 6.
received string: "3", size: 2.
The documentation for async_read_some
is very clear:
Remarks
The read operation may not read all of the requested number of bytes. Consider using the
async_read
function if you need to ensure that the requested amount of data is read before the asynchronous operation completes.
TCP is a stream based protocol, you will need to handle the message framing at the application layer. This largely depends on your protocol, one possible solution in your scenario may be to null terminate each message. Alternatively, include a fixed byte header before each message indicating the length of the payload.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.