Implement simple listening

This commit is contained in:
Sofia 2026-07-15 21:57:24 +03:00
parent e2960002a2
commit 0e2166fea4
2 changed files with 25 additions and 2 deletions

View File

@ -4,3 +4,5 @@ version = "0.1.0"
edition = "2024"
[dependencies]
thiserror = "2.0.18"
## Make it easier to generate errors

View File

@ -1,2 +1,23 @@
#[derive(Default)]
pub struct Peer {}
use std::net::{SocketAddr, UdpSocket};
use thiserror::*;
#[derive(Error, Debug)]
pub enum PeerError {
#[error("Error binding to port: {0}")]
BindError(std::io::Error),
}
pub struct Peer {
socket: UdpSocket,
}
impl Peer {
/// Bind given port to listen to incoming messages. Creates a new Peer that
/// can establish new connections.
pub fn listen(port: Option<u16>) -> Result<Peer, PeerError> {
let socket = UdpSocket::bind(SocketAddr::from(([0, 0, 0, 0], port.unwrap_or(0))))
.map_err(|e| PeerError::BindError(e))?;
Ok(Peer { socket })
}
}