rust UdpSocket 通信

180it 2023-03-11 AM 348℃ 0条
use std::net::UdpSocket;
use std::str;

fn main() -> std::io::Result<()> {
    let remote_addr = "localhost:8888";
    let socket = UdpSocket::bind("localhost:0")?;
    println!("Sending to the server");

    socket.send_to("Hello from client".as_bytes(), remote_addr)?;
    let mut buf = [0u8; 1500];
    let (length, _) = socket.recv_from(&mut buf)?;

    println!(
        "Received: {}",
        str::from_utf8(&buf[..length]).expect("buf is not utf-8")
    );

    Ok(())
}



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

fn main() -> std::io::Result<()> {
    println!("The server is running at localhost:8888");
    let socket = UdpSocket::bind("localhost:8888")?;

    loop {
        let mut buf = [0u8; 1500];
        let (length, remote_addr) = socket.recv_from(&mut buf)?;

        println!(
            "Received from {}: {}",
            remote_addr,
            str::from_utf8(&buf[..length]).expect("buf is not utf-8")
        );

        socket.send_to("Hello from Server".as_bytes(), remote_addr)?;
    }
}

支付宝打赏支付宝打赏 微信打赏微信打赏

如果文章或资源对您有帮助,欢迎打赏作者。一路走来,感谢有您!

标签: none

rust UdpSocket 通信