简体   繁体   English

从缓冲区大小提升asio udp async_read_

[英]boost asio udp async_read_from buffersize

I was reading the UDP daytime example from boost asio tutorial. 我正在阅读boost asio教程中的UDP daytime example It uses a recv_buffer_ and uses async_receive_from() to run the receiving loop. 它使用recv_buffer_并使用async_receive_from()运行接收循环。

socket_.async_receive_from(
    boost::asio::buffer(recv_buffer_), remote_endpoint_,
    boost::bind(&udp_server::handle_receive, this,
      boost::asio::placeholders::error,
      boost::asio::placeholders::bytes_transferred));

What I don't understand is 我不明白的是

boost::array<char, 1> recv_buffer_;

why its size is one ? 为什么它的大小是一个? what if the message received in more than one byte long ? 如果收到的消息超过一个字节长怎么办?

EDIT 编辑

as @Guy Sirton pointed I missed hsi part which was written in that page. 正如@Guy Sirton指出的那样,我错过了该页面上写的hsi部分。

Since we only provide the 1-byte recv_buffer_ to contain the client's request, the io_service object would return an error if the client sent anything larger. 由于我们仅提供1个字节的recv_buffer_来包含客户端的请求,因此,如果客户端发送了更大的内容,则io_service对象将返回错误。 We can ignore such an error if it comes up. 如果出现这种错误,我们可以忽略。

But is there anyway to read the entire message without having a buffer size ? 但是总有没有缓冲区大小的情况下可以读取整个消息吗? like looping receive_some by each character and storing in a string ? 如循环receive_some每个字符和字符串存储?

A buffer size is required. 缓冲区大小是必需的。

UDP preserves message boundaries. UDP保留消息边界。 When data is read from a socket, it will read up to the message boundary, even if the size of the provided buffer is smaller than the message. 从套接字读取数据时,即使提供的缓冲区的大小小于消息的大小,它也会读取到消息边界。 When the message size is larger than that of the buffer, the error code will be set to boost::asio::error::message_size . 当消息大小大于缓冲区大小时,错误代码将设置为boost::asio::error::message_size

Either allocate a buffer large enough to read the maximum expected message size or use reactor-style operations to lazily allocate the buffer. 分配足够大的缓冲区以读取最大预期消息大小,或者使用反应堆样式的操作来延迟分配缓冲区。

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

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