简体   繁体   English

Boost.Asio什么时候调用async_read_some回调?

[英]when does Boost.Asio call async_read_some callbacks?

Lets say I have a Boos.Asio TCP client, that can send a string, like this: 可以说我有一个Boos.Asio TCP客户端,它可以发送一个字符串,如下所示:

client.sendStr("1111");

I also have a asynchronous Boost.Asio TCP server, that will handle incoming packets and print them, like this: 我也有一个异步Boost.Asio TCP服务器,它将处理传入的数据包并进行打印,如下所示:

received string: "1111", size: 5.

Problem is, that when I call client.sendStr() multiple times, like this 问题是,当我多次调用client.sendStr() ,像这样

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". 我是网络新手,但我想这种情况的原因是TCP是“基于流的协议”。

My questions are: 我的问题是:

1) Can I prevent Boost.Asio from doing this? 1)我可以阻止Boost.Asio这样做吗? (lets say "1111" and "2222" are control packets of my application, and I don't what them to be connected). (让我们说“ 1111”和“ 2222”是我的应用程序的控制数据包,但我没有连接它们)。

2) Is there a possibility that I will get callbacks like this: 2)有没有可能我会收到这样的回调:

received string: "111122", size: 7.
received string: "22333", size: 6.
received string: "3", size: 2.

The documentation for async_read_some is very clear: async_read_some文档非常清楚:

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. 如果需要确保在异步操作完成之前读取请求的数据量,请考虑使用async_read函数。

TCP is a stream based protocol, you will need to handle the message framing at the application layer. TCP是基于流的协议,您将需要在应用程序层处理消息帧。 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. 或者,在每个指示有效载荷长度的消息之前包括一个固定的字节头。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM