Struct mio_st::net::UdpSocket

source ·
pub struct UdpSocket { /* private fields */ }
Expand description

A User Datagram Protocol socket.

This works much like the UdpSocket in the standard library, but the send_to, recv_from and peek_from methods don’t block and instead return a WouldBlock error.

Deregistering

UdpSocket will deregister itself when dropped.

Examples

An simple echo program, the sender sends a message and the echoer listens for messages and prints them to standard out.

use std::time::Duration;

use mio_st::event::{Events, EventedId, Ready};
use mio_st::net::UdpSocket;
use mio_st::poll::{Interests, PollOption, Poller};

// Unique ids and address for both the sender and echoer.
const SENDER_ID: EventedId = EventedId(0);
const ECHOER_ID: EventedId = EventedId(1);

let sender_address = "127.0.0.1:7000".parse()?;
let echoer_address = "127.0.0.1:7001".parse()?;

// Create our sockets.
let mut sender_socket = UdpSocket::bind(sender_address)?;
let mut echoer_socket = UdpSocket::bind(echoer_address)?;

// Connect the sockets so we can use `send` and `recv`, rather then
// `send_to` and `recv_from`.
let mut sender_socket = sender_socket.connect(echoer_address)?;
let mut echoer_socket = echoer_socket.connect(sender_address)?;

// As always create our poll and events.
let mut poller = Poller::new()?;
let mut events = Events::new();

// Register our sockets
poller.register(&mut sender_socket, SENDER_ID, Interests::WRITABLE, PollOption::Level)?;
poller.register(&mut echoer_socket, ECHOER_ID, Interests::READABLE, PollOption::Level)?;

// The message we'll send.
const MSG_TO_SEND: &[u8; 11] = b"Hello world";
// A buffer for our echoer to receive the message in.
let mut buf = [0; 11];

// Our event loop.
loop {
    poller.poll(&mut events, None)?;

    for event in &mut events {
        match event.id() {
            // Our sender is ready to send.
            SENDER_ID => {
                let bytes_sent = sender_socket.send(MSG_TO_SEND)?;
                assert_eq!(bytes_sent, MSG_TO_SEND.len());
                println!("sent {:?} ({} bytes)", MSG_TO_SEND, bytes_sent);
            },
            // Our echoer is ready to read.
            ECHOER_ID => {
                let bytes_recv = echoer_socket.recv(&mut buf)?;
                println!("{:?} ({} bytes)", &buf[0..bytes_recv], bytes_recv);
            }
            // We shouldn't receive any event with another id then the two
            // defined above.
            _ => unreachable!("received an unexpected event")
        }
    }
}

Implementations§

The interests to use when registering to receive both readable and writable events.

Creates a UDP socket and binds it to the given address.

Examples
use mio_st::net::UdpSocket;

// We must bind it to an open address.
let address = "127.0.0.1:7002".parse()?;
let socket = UdpSocket::bind(address)?;

// Our socket was created, but we should not use it before checking it's
// readiness.

Connects the UDP socket by setting the default destination and limiting packets that are read, written and peeked to the address specified in address.

See ConnectedUdpSocket for more information.

Returns the socket address that this socket was created from.

Examples
use mio_st::net::UdpSocket;

let address = "127.0.0.1:7003".parse()?;
let mut socket = UdpSocket::bind(address)?;

assert_eq!(socket.local_addr()?, address);

Sends data to the given address. On success, returns the number of bytes written.

Examples
use mio_st::net::UdpSocket;

let address = "127.0.0.1:7004".parse()?;
let mut socket = UdpSocket::bind(address)?;

// We must check if the socket is writable before calling send_to,
// or we could run into a WouldBlock error.

let other_address = "127.0.0.1:7005".parse()?;
let bytes_sent = socket.send_to(&[9; 9], other_address)?;
assert_eq!(bytes_sent, 9);

Receives data from the socket. On success, returns the number of bytes read and the address from whence the data came.

Examples
use mio_st::net::UdpSocket;

let address = "127.0.0.1:7006".parse()?;
let mut socket = UdpSocket::bind(address)?;

// We must check if the socket is readable before calling recv_from,
// or we could run into a WouldBlock error.

let mut buf = [0; 9];
let (num_recv, from_addr) = socket.recv_from(&mut buf)?;
println!("Received {:?} -> {:?} bytes from {:?}", buf, num_recv, from_addr);

Receives data from the socket, without removing it from the input queue. On success, returns the number of bytes read and the address from whence the data came.

Examples
use mio_st::net::UdpSocket;

let address = "127.0.0.1:7007".parse()?;
let mut socket = UdpSocket::bind(address)?;

// We must check if the socket is readable before calling recv_from,
// or we could run into a WouldBlock error.

let mut buf1 = [0; 9];
let mut buf2 = [0; 9];
let (num_recv1, from_addr1) = socket.peek_from(&mut buf1)?;
let (num_recv2, from_addr2) = socket.recv_from(&mut buf2)?;
assert_eq!(num_recv1, num_recv2);
assert_eq!(from_addr1, from_addr2);
assert_eq!(buf1, buf2);

Get the value of the SO_ERROR option on this socket.

This will retrieve the stored error in the underlying socket, clearing the field in the process. This can be useful for checking errors between calls.

Trait Implementations§

Extracts the raw file descriptor. Read more
Formats the value using the given formatter. Read more
Register self with the given Poller instance. Read more
Reregister self with the given Poller instance. Read more
Deregister self from the given Poller instance Read more
Constructs a new instance of Self from the given raw file descriptor. Read more
Consumes this object, returning the raw underlying file descriptor. Read more

Auto Trait Implementations§

Blanket Implementations§

Gets the TypeId of self. Read more
Immutably borrows from an owned value. Read more
Mutably borrows from an owned value. Read more

Returns the argument unchanged.

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

The type returned in the event of a conversion error.
Performs the conversion.
The type returned in the event of a conversion error.
Performs the conversion.