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§
source§impl UdpSocket
impl UdpSocket
sourcepub const INTERESTS: Interests = Interests::BOTH
pub const INTERESTS: Interests = Interests::BOTH
The interests to use when registering to receive both readable and writable events.
sourcepub fn bind(address: SocketAddr) -> Result<UdpSocket>
pub fn bind(address: SocketAddr) -> Result<UdpSocket>
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.
sourcepub fn connect(self, address: SocketAddr) -> Result<ConnectedUdpSocket>
pub fn connect(self, address: SocketAddr) -> Result<ConnectedUdpSocket>
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.
sourcepub fn local_addr(&mut self) -> Result<SocketAddr>
pub fn local_addr(&mut self) -> Result<SocketAddr>
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);
sourcepub fn send_to(&mut self, buf: &[u8], target: SocketAddr) -> Result<usize>
pub fn send_to(&mut self, buf: &[u8], target: SocketAddr) -> Result<usize>
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);
sourcepub fn recv_from(&mut self, buf: &mut [u8]) -> Result<(usize, SocketAddr)>
pub fn recv_from(&mut self, buf: &mut [u8]) -> Result<(usize, SocketAddr)>
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);
sourcepub fn peek_from(&mut self, buf: &mut [u8]) -> Result<(usize, SocketAddr)>
pub fn peek_from(&mut self, buf: &mut [u8]) -> Result<(usize, SocketAddr)>
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);
sourcepub fn take_error(&mut self) -> Result<Option<Error>>
pub fn take_error(&mut self) -> Result<Option<Error>>
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.