收听 udpsocket 时需要一个动态大小的缓冲区

Need a dynamic size buffer when listening to a udpsocket

这是当前监听udpsocket端口的代码:34254

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

fn main() -> std::io::Result<()> {
    {
        let socket = UdpSocket::bind("127.0.0.1:34254").expect("couldn't bind to address");
        socket.connect("127.0.0.1:34254").expect("connect function failed");
        println!("ready");
        let mut buf = [0; 2048];
        match socket.recv(&mut buf) {
            Ok(_received) =>{
                let s = match str::from_utf8(&buf) {
                    Ok(v) => v,
                    Err(e) => panic!("Invalid UTF-8 sequence: {}", e),
                };
                println!("result: {}", s);
            },
            Err(e) => println!("recv function failed: {:?}", e),
        }
    } // the socket is closed here
    Ok(())
}

现在,我的数据长度会有所不同,我不能给出像“2048”这样的大小,否则当我发送更大的数据时缓冲区会 运行。

我可以创建一个动态大小的缓冲区(或类似的东西),我知道 socket.send 方法有一个长度参数,我可以利用它吗?

Now, the length of my data will vary and I cannot give a size like "2048"

你有没有把你数据的长度信息打包到数据包中?比如前导4个字节包含了整个数据包的长度。

如果你有这样的信息,你可以使用 UdpSocket::peek:

Receives single datagram on the socket from the remote address to which it is connected, without removing the message from input queue. On success, returns the number of bytes peeked.

然后你可以得到一个数字的长度,然后分配正确数量的 space 并调用。

但一切都需要权衡,它需要一个额外的系统调用,这可能比从堆栈中获取一些 space 更昂贵。

或者,您可以提前分配一个“足够大”的数组。