Skip to content

Instantly share code, notes, and snippets.

@rsolomo
Last active July 15, 2022 14:19
Show Gist options
  • Save rsolomo/8703190 to your computer and use it in GitHub Desktop.
Save rsolomo/8703190 to your computer and use it in GitHub Desktop.
trying out creating a udp listener in Rust
use std::io::net::ip;
use std::io::net::udp;
use std::str;
fn main() {
let addr = ip::SocketAddr {
ip: ip::Ipv4Addr(127, 0, 0, 1),
port: 5514
};
let mut socket = match udp::UdpSocket::bind(addr) {
Ok(s) => s,
Err(e) => fail!("couldn't bind socket: {}", e)
};
let mut buf = [0, ..2048];
loop {
match socket.recv_from(buf) {
Ok((amt, src)) => spawn(proc() {
println!("amt: {}", amt);
println!("src: {}", src);
println!("{}", str::from_utf8(buf).unwrap_or(""));
}),
Err(e) => println!("couldn't recieve a datagram: {}", e)
}
}
}
@jezzarax
Copy link

Updated the code for the latest version of rust:

use std::str;
use std::thread;
use std::net::UdpSocket;

fn main() {

    let socket = match UdpSocket::bind("0.0.0.0:5514") {
        Ok(s) => s,
        Err(e) => panic!("couldn't bind socket: {}", e)
    };

    let mut buf = [0; 2048];
    loop {
        match socket.recv_from(&mut buf) {
            Ok((amt, src)) => {
                thread::spawn(move || {
                    println!("amt: {}", amt);
                    println!("src: {}", src);
                    println!("{}", str::from_utf8(&buf).unwrap_or(""));
                });
            },
            Err(e) => {
                println!("couldn't recieve a datagram: {}", e);
            }
        }
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment