What size buffer should be used for reading from a UDP socket?

北战南征 提交于 2019-12-08 14:09:25

问题


When reading data from a std::net::UdpSocket in Rust we use a buffer:

fn recv_from(&self, buf: &mut [u8]) -> Result<(usize, SocketAddr)>

How big should this buffer be? Is the socket a stream or a datagram?


回答1:


You should use a size one larger than the largest expected datagram. That way, if you receive one that size, you know there was a protocol error and that data may have been truncated.

You will receive one datagram at a time. It's not a stream.




回答2:


You may try to use the receive/transmit buffer sizes that match the socket receive/transmit options, see SO_SNDBUF and SO_RCVBUF on Linux sockets, getsockopt(3), SO_RCVBUF, and SO_SNDBUF.

Alternatively, you may use buffer sizes that match and align well with your protocol structures.

The larger the buffer size in your program is, the less IO calls you perform. In the case where you assemble payload from multiple disjoint memory locations, you may use scatter / gather IO vectors to minimize IO syscalls.



来源:https://stackoverflow.com/questions/36333976/what-size-buffer-should-be-used-for-reading-from-a-udp-socket

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!