听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”之类的大小,或者当我发送更大的数据时,缓冲区将用完。
我可以创建一个动态的大小缓冲区(或类似的东西),我知道插入方法具有长度参数,我可以利用这一点吗?
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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您是否将数据的长度信息包装到数据包数据中?例如,主要的4个字节包含整个数据包的长度。
如果您有此类信息,则可以使用 udpsocket :: peek :
然后,您可以将长度作为数字获得,然后完全分配适量的空间和呼叫。
但是,一切都带来了权衡,它需要额外的系统调用,这比从堆栈中获得一些空间可能要贵。
或者,您只需提前分配一个“足够大”的阵列。
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:
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.
对于任何绊倒此线程的人:一个UDP数据报具有IPv4的上限限制,IPv4的尺寸为65,507字节,IPv6的字节为65,527个字节。可以使用足够大小的堆分配的数组(
box&lt; [u8; 65527]&gt;
)来接收所有包装最高。尺寸。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.