连接超时,我试图连接到使用下面的代码是可达服务器:如何设置上TcpStream
println!("Connecting");
TcpStream::connect(s).unwrap();
println!("Connected");
当我运行的代码,它卡住在第二行。
输出:
Connecting
连接超时,我试图连接到使用下面的代码是可达服务器:如何设置上TcpStream
println!("Connecting");
TcpStream::connect(s).unwrap();
println!("Connected");
当我运行的代码,它卡住在第二行。
输出:
Connecting
它不是目前能够改变上制作一个TCP连接的超时。网络堆栈将拥有自己的默认设置,这些默认设置可能因操作系统而异;我相信一分钟是典型的超时时间。
没有简单,标准的方法来做到这一点,所以我通过nix crate将this answer移植到了Rust上做了一些小小的改动:一旦建立连接,将套接字重新设置为阻塞状态,以便它可以与Rust的std I/O一起使用,当然也可以用std::net::TcpStream
包装。
这里是回购:https://github.com/filsmick/rust-tcp-connection-timeout
从SRC/lib.rs:
pub fn tcp_connect_with_timeout(socket_addr: std::net::SocketAddr, timeout: Duration) -> Result<TcpStream, ConnectionError> {
// Create a socket file descriptor.
let socket_fd = try!(nix::sys::socket::socket(
nix::sys::socket::AddressFamily::Inet,
nix::sys::socket::SockType::Stream,
nix::sys::socket::SockFlag::empty()
));
// Set the socket to non-blocking mode so we can `select()` on it.
try!(nix::fcntl::fcntl(
socket_fd,
nix::fcntl::FcntlArg::F_SETFL(nix::fcntl::O_NONBLOCK)
));
let connection_result = nix::sys::socket::connect(
socket_fd,
&(nix::sys::socket::SockAddr::Inet(nix::sys::socket::InetAddr::from_std(&socket_addr)))
);
match connection_result {
Ok(_) =>(),
Err(e) => {
match e {
nix::Error::Sys(errno) => {
match errno {
nix::errno::Errno::EINPROGRESS =>(), // socket is non-blocking so an EINPROGRESS is to be expected
_ => return Err(ConnectionError::from(e))
}
}
nix::Error::InvalidPath => unreachable!() //
}
}
}
let mut timeout_timeval = nix::sys::time::TimeVal {
tv_sec: timeout.as_secs() as i64,
tv_usec: timeout.subsec_nanos() as i32
};
// Create a new fd_set monitoring our socket file descriptor.
let mut fdset = nix::sys::select::FdSet::new();
fdset.insert(socket_fd);
// `select()` on it, will return when the connection succeeds or times out.
let select_res = try!(nix::sys::select::select(
socket_fd + 1,
None,
Some(&mut fdset),
None,
&mut timeout_timeval
));
// This it what fails if `addr` is unreachable.
if select_res != 1 {
println!("select return value: {}", select_res);
return Err(ConnectionError::SelectError);
}
// Make sure the socket encountered no error.
let socket_error_code = try!(nix::sys::socket::getsockopt(
socket_fd,
nix::sys::socket::sockopt::SocketError
));
if socket_error_code != 0 {
return Err(ConnectionError::SocketError(socket_error_code));
}
// Set the socket back to blocking mode so it can be used with std's I/O facilities.
try!(nix::fcntl::fcntl(
socket_fd,
nix::fcntl::FcntlArg::F_SETFL(nix::fcntl::OFlag::empty())
));
// Wrap it in a TcpStream and return that stream.
Ok(
unsafe { TcpStream::from_raw_fd(socket_fd) }
)
}
ConnectionError
在error.rs
定义,但如果你想通过解包,而不是使用try!
您可以忽略它。
虽然有一个问题:select
在编写本文时尚未在主要的nix库中实现,但有一个pending Pull Request,因此您必须在此期间依靠叉(它不应该尽管):
[dependencies]
nix = { git = "https://github.com/utkarshkukreti/nix-rust.git", branch = "add-sys-select" }
不是永远。它应该在一分钟后超时。 – EJP