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

发布于 2025-01-26 22:54:03 字数 945 浏览 3 评论 0原文

这是当前在端口上收听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”之类的大小,或者当我发送更大的数据时,缓冲区将用完。

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

This is the current code listening to the udpsocket at port: 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(())
}

Now, the length of my data will vary and I cannot give a size like "2048", or the buffer will run out when I send bigger data.

Can I create a dynamic size buffer (or something similar), I know that socket.send method has a length parameter, can I take advantage of that?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

静水深流 2025-02-02 22:54:03

现在,我的数据长度会有所不同,我不能给出“ 2048”之类的大小

您是否将数据的长度信息包装到数据包数据中?例如,主要的4个字节包含整个数据包的长度。

如果您有此类信息,则可以使用 udpsocket :: peek

从其连接的远程地址接收套接字上的单个数据报,而无需从输入队列中删除消息。成功,返回窥视字节的数量。

然后,您可以将长度作为数字获得,然后完全分配适量的空间和呼叫。

但是,一切都带来了权衡,它需要额外的系统调用,这比从堆栈中获得一些空间可能要贵。

或者,您只需提前分配一个“足够大”的阵列。

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

Do you have packed the length information of your data into the packet data? For example, the leading 4 bytes containing the length of the entire packet.

If you have such information, you could use the 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.

Then you could get the length as a number, then allocate exactly the right amount of space and call.

But everything comes with a tradeoff, it needs an extra system call, which could be more expensive than getting some space from the stack.

Or, you could, just simply allocate a "big enough" array ahead of time.

空气里的味道 2025-02-02 22:54:03

对于任何绊倒此线程的人:一个UDP数据报具有IPv4的上限限制,IPv4的尺寸为65,507字节,IPv6的字节为65,527个字节。可以使用足够大小的堆分配的数组(box&lt; [u8; 65527]&gt;)来接收所有包装最高。尺寸。

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: Box<[u8; 65527]> = Box::new([0; 65527]);
        match socket.recv(buf.as_mut_slice()) {
            Ok(n) =>{  // n is the number of received bytes
                let s = match str::from_utf8(&buf[..n]) {  // reading up to n
                    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(())
}

For anybody stumbling upon this thread: A UDP datagram has an upper size limit which is 65,507 bytes for IPv4 and 65,527 bytes for IPv6. A sufficient sized heap allocated array (Box<[u8; 65527]>) can be used to to receive all package up to the max. size.

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: Box<[u8; 65527]> = Box::new([0; 65527]);
        match socket.recv(buf.as_mut_slice()) {
            Ok(n) =>{  // n is the number of received bytes
                let s = match str::from_utf8(&buf[..n]) {  // reading up to n
                    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(())
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文