netcode/
transceiver.rs

1use std::net::SocketAddr;
2
3use crate::error::Error;
4
5/// A trait for sending and receiving data.
6///
7/// Both the server and client use a statically dispatched generic type `T: Transceiver` to send and receive data,
8/// which allows you to use any type that implements this trait as your network socket for a `netcode` server or client.
9///
10/// See [`NetcodeSocket`](https://github.com/benny-n/netcode/blob/0147a2d11cb48dea59a637ca2f017912f3f6d9aa/src/socket.rs#L37) for an example implementation.
11/// This is also the default implementation used by the server and client.
12pub trait Transceiver {
13    type IntoError: Into<Error>;
14    /// Returns the local address of the socket (i.e. the address it is bound to).
15    ///
16    /// Mostly used for generating and validating [`ConnectTokens`](crate::ConnectToken).
17    fn addr(&self) -> SocketAddr;
18    /// Receives a packet from the socket, if one is available.
19    ///
20    /// Should **NOT** block if no packet is available.
21    fn recv(&self, buf: &mut [u8]) -> Result<Option<(usize, SocketAddr)>, Self::IntoError>;
22    /// Sends a packet to the specified address.
23    ///
24    /// Should **NOT** block if the packet cannot be sent.
25    fn send(&self, buf: &[u8], addr: SocketAddr) -> Result<usize, Self::IntoError>;
26}