Timmmm
Timmmm

Reputation: 97058

How do I poll a std::net::UdpSocket?

With Rust's UdpSocket, it appears to only have send(), recv(), and set_nonblocking(bool). This is a rather limited set of functions, e.g. it would be nice to have recv() which always blocks until a packet is received and recv_nonblocking() which never blocks, and maybe even recv_callback() that calls a function when a packet is received.

Is there any way to do recv_nonblocking() other than something insane like this:

fn recv_nonblocking(socket: &UdpSocket, buf: &mut [u8]) -> Result<usize> {

    try!(socket.set_nonblocking(true));

    // By the way, how do I know how big to make my buffer?
    // There doesn't seem to be any way to know the size of a packet
    // before it is returned by socket.recv().

    let res = socket.recv(&mut buf);

    // This isn't really right either because there is no get_nonblocking()
    // so we can't reliably restore the previous state.
    try!(socket.set_nonblocking(false));

    res
}

Would that even work?

Upvotes: 2

Views: 1390

Answers (2)

notriddle
notriddle

Reputation: 668

recv_nonblocking

Just call set_nonblocking and then recv. If you're really going to use both blocking and nonblocking I/O on the same socket, you can write trivial wrapper functions:

fn recv_nonblocking(this: &UdpSocket, buf: &mut [u8]) -> io::Result<usize> {
    this.set_nonblocking(true);
    this.recv(buf)
}

recv_callback

Good asynchronous I/O primitives have been left out of the standard library, so that the design work can be iterated on without locking down to the stability guarantees and release cycle of the language.

The crate to look at is mio.

Upvotes: 3

dpc.pw
dpc.pw

Reputation: 3466

Generally you either use blocking or non-blocking mode through the whole lifecycle of the socket. In blocking mode you can use set_read_timeout get_read_timeout instead.

Upvotes: 0

Related Questions