What size buffer should be used for reading from a

2019-06-14 17:34发布

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?

2条回答
姐就是有狂的资本
2楼-- · 2019-06-14 18:16

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.

查看更多
不美不萌又怎样
3楼-- · 2019-06-14 18:22

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.

查看更多
登录 后发表回答