Struct heph::net::udp::UdpSocket[][src]

pub struct UdpSocket<M = Unconnected> { /* fields omitted */ }
Expand description

A User Datagram Protocol (UDP) socket.

To create a UDP socket UdpSocket::bind can be used, this will bind the socket to a local address. The created socket will be in unconnected mode. A socket can be in one of two modes:

  • Unconnected mode allows sending and receiving packets to and from all sources.
  • Connected mode only allows sending and receiving packets from/to a single source.

An unconnected socket can be connected to a specific address if needed, changing the mode to Connected in the process. The remote address of an already connected socket can be changed to a different address using the same method.

Both unconnected and connected sockets have three main operations send, receive and peek, all these methods return a Future.

Examples

#![feature(never_type)]

use std::net::SocketAddr;
use std::{io, str};

use log::error;

use heph::actor::messages::Terminate;
use heph::net::UdpSocket;
use heph::rt::{self, Runtime, RuntimeRef, ThreadLocal};
use heph::spawn::ActorOptions;
use heph::util::either;
use heph::{actor, SupervisorStrategy};

fn main() -> Result<(), rt::Error> {
    std_logger::init();

    let mut runtime = Runtime::new()?;
    runtime.run_on_workers(setup)?;
    runtime.start()
}

fn setup(mut runtime: RuntimeRef) -> Result<(), !> {
    let address = "127.0.0.1:7000".parse().unwrap();
    // Add our server actor.
    runtime.spawn_local(supervisor, echo_server as fn(_, _) -> _, address, ActorOptions::default());
    // Add our client actor.
    runtime.spawn_local(supervisor, client as fn(_, _) -> _, address, ActorOptions::default());
    Ok(())
}

/// Simple supervisor that logs the error and stops the actor.
fn supervisor<Arg>(err: io::Error) -> SupervisorStrategy<Arg> {
    error!("Encountered an error: {}", err);
    SupervisorStrategy::Stop
}

/// Actor that will bind a UDP socket and waits for incoming packets and
/// echos the message to standard out.
async fn echo_server(mut ctx: actor::Context<Terminate, ThreadLocal>, local: SocketAddr) -> io::Result<()> {
    let mut socket = UdpSocket::bind(&mut ctx, local)?;
    let mut buf = Vec::with_capacity(4096);
    loop {
        buf.clear();
        let receive_msg = ctx.receive_next();
        let read = socket.recv_from(&mut buf);
        let address = match either(read, receive_msg).await {
            // Received a packet.
            Ok(Ok((_, address))) => address,
            // Read error.
            Ok(Err(err)) => return Err(err),
            // If we receive a terminate message we'll stop the actor.
            Err(_) => return Ok(()),
        };

        match str::from_utf8(&buf) {
            Ok(str) => println!("Got the following message: `{}`, from {}", str, address),
            Err(_) => println!("Got data: {:?}, from {}", buf, address),
        }
    }
}

/// The client that will send a message to the server.
async fn client(mut ctx: actor::Context<!, ThreadLocal>, server_address: SocketAddr) -> io::Result<()> {
    let local_address = "127.0.0.1:7001".parse().unwrap();
    let mut socket = UdpSocket::bind(&mut ctx, local_address)
        .and_then(|socket| socket.connect(server_address))?;

    let msg = b"Hello world";
    let n = socket.send(&*msg).await?;
    assert_eq!(n, msg.len());
    Ok(())
}

Implementations

Create a UDP socket binding to the local address.

Notes

The UDP socket is also bound to the actor that owns the actor::Context, which means the actor will be run every time the socket is ready to be read from or write to.

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

Returns the sockets local address.

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.

Attempt to send data to the given target address.

If the buffer currently can’t be send this will return an error with the kind set to ErrorKind::WouldBlock. Most users should prefer to use UdpSocket::send_to.

Sends data to the given target address. Returns a Future that on success returns the number of bytes written (io::Result<usize>).

Attempt to send bytes in bufs to the peer.

If no bytes can currently be send this will return an error with the kind set to ErrorKind::WouldBlock. Most users should prefer to use UdpSocket::send_to_vectored.

Send the bytes in bufs to the peer.

Returns the number of bytes written. This may be fewer then the length of bufs.

Attempt to receive data from the socket, writing them into buf.

If no bytes can currently be received this will return an error with the kind set to ErrorKind::WouldBlock. Most users should prefer to use UdpSocket::recv_from.

Receives data from the socket. Returns a Future that on success returns the number of bytes read and the address from whence the data came (io::Result<(usize, SocketAddr>).

Attempt to receive data from the socket, writing them into bufs.

If no bytes can currently be received this will return an error with the kind set to ErrorKind::WouldBlock. Most users should prefer to use UdpSocket::recv_from.

Receives data from the socket. Returns a Future that on success returns the number of bytes read and the address from whence the data came (io::Result<(usize, SocketAddr>).

Attempt to peek data from the socket, writing them into buf.

If no bytes can currently be peeked this will return an error with the kind set to ErrorKind::WouldBlock. Most users should prefer to use UdpSocket::peek_from.

Receives data from the socket, without removing it from the input queue. Returns a Future that on success returns the number of bytes read and the address from whence the data came (io::Result<(usize, SocketAddr>).

Attempt to peek data from the socket, writing them into bufs.

If no bytes can currently be received this will return an error with the kind set to ErrorKind::WouldBlock. Most users should prefer to use UdpSocket::recv_vectored.

Receives data from the socket, without removing it from the input queue. Returns a Future that on success returns the number of bytes read and the address from whence the data came (io::Result<(usize, SocketAddr>).

Attempt to send data to the peer.

If the buffer currently can’t be send this will return an error with the kind set to ErrorKind::WouldBlock. Most users should prefer to use UdpSocket::send_to.

Sends data on the socket to the connected socket. Returns a Future that on success returns the number of bytes written (io::Result<usize>).

Attempt to send bytes in bufs to the peer.

If no bytes can currently be send this will return an error with the kind set to ErrorKind::WouldBlock. Most users should prefer to use UdpSocket::send_vectored.

Send the bytes in bufs to the peer.

Returns the number of bytes written. This may we fewer then the length of bufs.

Attempt to receive data from the socket, writing them into buf.

If no bytes can currently be received this will return an error with the kind set to ErrorKind::WouldBlock. Most users should prefer to use UdpSocket::recv.

Receives data from the socket. Returns a Future that on success returns the number of bytes read (io::Result<usize>).

Attempt to receive data from the socket, writing them into bufs.

If no bytes can currently be received this will return an error with the kind set to ErrorKind::WouldBlock. Most users should prefer to use UdpSocket::recv_vectored.

Receives data from the socket. Returns a Future that on success returns the number of bytes read (io::Result<usize>).

Attempt to peek data from the socket, writing them into buf.

If no bytes can currently be peeked this will return an error with the kind set to ErrorKind::WouldBlock. Most users should prefer to use UdpSocket::peek.

Receives data from the socket, without removing it from the input queue. Returns a Future that on success returns the number of bytes read (io::Result<usize>).

Attempt to peek data from the socket, writing them into bufs.

If no bytes can currently be received this will return an error with the kind set to ErrorKind::WouldBlock. Most users should prefer to use UdpSocket::recv_vectored.

Receives data from the socket, without removing it from the input queue. Returns a Future that on success returns the number of bytes read (io::Result<usize>).

Trait Implementations

Error type used in bind_to. Read more

Bind a type to the Actor that owns the ctx.

Formats the value using the given formatter. 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

Performs the conversion.

Performs the conversion.

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.