如何为std::net::UdpSocket设置超时?
How to set timeout for std::net::UdpSocket?
std::old_io::net::udp::UdpSocket has been replaced with std::net::UdpSocket,fn set_timeout(&mut self, timeout_ms: Option<u64>)
没有等价物。
有什么实现方法吗?
目前无法为 std::net
中的任何网络操作设置超时。上面有一个 RFC,所以对于 Rust 1.0,它肯定会被修复。敬请期待!
在此期间您可以使用 AsRawFd
implementation which each socket has and call low-level socket functions on the file descriptor manually. AsRawFd::as_raw_fd()
returns raw file descriptor which represents the underlying socket in the operating system. You can call various low-level socket functions on this file descriptor, like setsockopt
. These functions are available through libc
crate. You can find how it could be done in libstd
sources, for example, here。您可能还想使用 crates.io 中的 libc
- 内置的位于功能门之后,因此在测试版中不可用。
为了设置 send/read 超时,您需要使用 SO_SNDTIMEO
/SO_RCVTIMEO
选项调用 setsockopt
,提供指向 timeval
实例的指针.这基本上就是如何在 C 中完成的。如果你愿意,我可以稍后(可能在几个小时内)对此进行扩展。
std::old_io::net::udp::UdpSocket has been replaced with std::net::UdpSocket,fn set_timeout(&mut self, timeout_ms: Option<u64>)
没有等价物。
有什么实现方法吗?
目前无法为 std::net
中的任何网络操作设置超时。上面有一个 RFC,所以对于 Rust 1.0,它肯定会被修复。敬请期待!
在此期间您可以使用 AsRawFd
implementation which each socket has and call low-level socket functions on the file descriptor manually. AsRawFd::as_raw_fd()
returns raw file descriptor which represents the underlying socket in the operating system. You can call various low-level socket functions on this file descriptor, like setsockopt
. These functions are available through libc
crate. You can find how it could be done in libstd
sources, for example, here。您可能还想使用 crates.io 中的 libc
- 内置的位于功能门之后,因此在测试版中不可用。
为了设置 send/read 超时,您需要使用 SO_SNDTIMEO
/SO_RCVTIMEO
选项调用 setsockopt
,提供指向 timeval
实例的指针.这基本上就是如何在 C 中完成的。如果你愿意,我可以稍后(可能在几个小时内)对此进行扩展。