pub struct UdpSocket { /* private fields */ }Expand description
A high-level UDP Socket that allows for writing and reading (de)serializable values
Implementations§
Source§impl UdpSocket
impl UdpSocket
Sourcepub async fn bind<A: ToSocketAddrs>(addr: A) -> Result<Self, UdpSocketError>
pub async fn bind<A: ToSocketAddrs>(addr: A) -> Result<Self, UdpSocketError>
Sourcepub fn new(socket: UdpSocket) -> Self
pub fn new(socket: UdpSocket) -> Self
Create a new UDP socket from an existing tokio::net::UdpSocket
§Example
use sockit::UdpSocket;
use tokio::net::UdpSocket as TokioUdpSocket;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let tokio_socket = TokioUdpSocket::bind("127.0.0.1:0").await?;
let mut sockit_socket = UdpSocket::new(tokio_socket);
Ok(())
}Sourcepub async fn write<T: Serialize>(
&mut self,
value: &T,
send_to: SocketAddr,
) -> Result<(), UdpSocketError>
pub async fn write<T: Serialize>( &mut self, value: &T, send_to: SocketAddr, ) -> Result<(), UdpSocketError>
Write a serializable value to the socket
§Example
use sockit::UdpSocket;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut socket = UdpSocket::bind("127.0.0.1:0").await?;
socket.write(&"Hello World!", "127.0.0.1:9090".parse()?).await?;
Ok(())
}Sourcepub async fn read<T: DeserializeOwned>(
&mut self,
) -> Result<(T, SocketAddr), UdpSocketError>
pub async fn read<T: DeserializeOwned>( &mut self, ) -> Result<(T, SocketAddr), UdpSocketError>
Read a deserializable value from a single datagram on the socket
This method returns an error when it isn’t possible to deserialize the value from the datagram. This can happen if the value doesn’t fit into a single datagram.
§Example
use sockit::UdpSocket;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut socket = UdpSocket::bind("127.0.0.1:0").await?;
let message = socket.read::<String>().await?;
Ok(())
}Sourcepub fn local_addr(&self) -> Result<SocketAddr, UdpSocketError>
pub fn local_addr(&self) -> Result<SocketAddr, UdpSocketError>
Get the local address of the socket
§Example
use sockit::UdpSocket;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let socket = UdpSocket::bind("127.0.0.1:0").await?;
let addr = socket.local_addr()?;
Ok(())
}Auto Trait Implementations§
impl !Freeze for UdpSocket
impl RefUnwindSafe for UdpSocket
impl Send for UdpSocket
impl Sync for UdpSocket
impl Unpin for UdpSocket
impl UnwindSafe for UdpSocket
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more