use std::io::prelude::*;
use std::net::{TcpStream, TcpListener};
use std::fmt;
use std::io::{self};
use net::{ToSocketAddrs, SocketAddr, Shutdown};
use sys_common::net as net_imp;
use sys_common::{AsInner, FromInner, IntoInner};
use std::time::Duration;
use {SOCKET, INVALID_SOCKET};
pub struct TcpSocket(net_imp::TcpSocket);
#[derive(Debug)]
pub struct Incoming<'a> { listener: &'a TcpSocket }
impl TcpSocket {
pub fn connect<A: ToSocketAddrs>(addr: A) -> io::Result<TcpSocket> {
super::each_addr(addr, net_imp::TcpSocket::connect).map(TcpSocket)
}
pub fn s_connect<A: ToSocketAddrs>(&self, addr: A) -> io::Result<()> {
super::each_addr(addr, |addr| {
self.0.s_connect(addr)
})
}
pub fn connect_timeout(addr: &SocketAddr, timeout: Duration) -> io::Result<TcpSocket> {
net_imp::TcpSocket::connect_timeout(addr, timeout).map(TcpSocket)
}
pub fn s_connect_timeout(&self, addr: &SocketAddr, timeout: Duration) -> io::Result<()> {
self.0.s_connect_timeout(addr, timeout)
}
pub fn connect_asyn(addr: &SocketAddr) -> io::Result<TcpSocket> {
net_imp::TcpSocket::connect_asyn(addr).map(TcpSocket)
}
pub fn s_connect_asyn(&self, addr: &SocketAddr) -> io::Result<()> {
self.0.s_connect_asyn(addr)
}
pub fn as_raw_socket(&self) -> SOCKET {
self.0.as_raw_socket()
}
pub fn new_by_fd(fd: SOCKET) -> io::Result<TcpSocket> {
net_imp::TcpSocket::new_by_fd(fd).map(TcpSocket)
}
pub fn new_invalid() -> io::Result<TcpSocket> {
net_imp::TcpSocket::new_by_fd(INVALID_SOCKET).map(TcpSocket)
}
pub fn is_valid(&self) -> bool {
self.0.is_valid()
}
pub fn is_ready(&self) -> bool {
self.0.is_ready()
}
pub fn set_ready(&self, ready: bool) {
self.0.set_ready(ready);
}
pub fn is_close(&self) -> bool {
self.0.is_close()
}
pub fn close(&self) {
self.0.close();
}
pub fn check_ready(&self) -> io::Result<bool> {
self.0.check_ready()
}
pub fn peer_addr(&self) -> io::Result<SocketAddr> {
self.0.peer_addr()
}
pub fn set_peer_addr(&mut self, addr: SocketAddr) {
self.0.set_peer_addr(addr);
}
pub fn local_addr(&self) -> io::Result<SocketAddr> {
self.0.socket_addr()
}
pub fn set_local_addr(&mut self, addr: SocketAddr) {
self.0.set_socket_addr(addr);
}
pub fn shutdown(&self, how: Shutdown) -> io::Result<()> {
self.0.shutdown(how)
}
pub fn try_clone(&self) -> io::Result<TcpSocket> {
self.0.duplicate().map(TcpSocket)
}
pub fn set_read_timeout(&self, dur: Option<Duration>) -> io::Result<()> {
self.0.set_read_timeout(dur)
}
pub fn set_write_timeout(&self, dur: Option<Duration>) -> io::Result<()> {
self.0.set_write_timeout(dur)
}
pub fn read_timeout(&self) -> io::Result<Option<Duration>> {
self.0.read_timeout()
}
pub fn write_timeout(&self) -> io::Result<Option<Duration>> {
self.0.write_timeout()
}
pub fn peek(&self, buf: &mut [u8]) -> io::Result<usize> {
self.0.peek(buf)
}
pub fn set_nodelay(&self, nodelay: bool) -> io::Result<()> {
self.0.set_nodelay(nodelay)
}
pub fn nodelay(&self) -> io::Result<bool> {
self.0.nodelay()
}
pub fn set_ttl(&self, ttl: u32) -> io::Result<()> {
self.0.set_ttl(ttl)
}
pub fn ttl(&self) -> io::Result<u32> {
self.0.ttl()
}
pub fn take_error(&self) -> io::Result<Option<io::Error>> {
self.0.take_error()
}
pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> {
self.0.set_nonblocking(nonblocking)
}
pub fn is_nonblocking(&self) -> bool {
self.0.is_nonblocking()
}
pub fn set_liner(&self, enable: bool, time: u16) -> io::Result<()> {
self.0.set_liner(enable, time)
}
pub fn liner(&self) -> io::Result<(bool, u16)> {
self.0.liner()
}
pub fn set_recv_size(&self, size: u32) -> io::Result<()> {
self.0.set_recv_size(size)
}
pub fn recv_size(&self) -> io::Result<u32> {
self.0.recv_size()
}
pub fn set_send_size(&self, size: u32) -> io::Result<()> {
self.0.set_send_size(size)
}
pub fn send_size(&self) -> io::Result<u32> {
self.0.send_size()
}
pub fn set_reuse_addr(&self) -> io::Result<()> {
self.0.set_reuse_addr()
}
pub fn set_reuse_port(&self) -> io::Result<()> {
self.0.set_reuse_port()
}
pub fn bind<A: ToSocketAddrs>(addr: A) -> io::Result<TcpSocket> {
super::each_addr(addr, net_imp::TcpSocket::bind).map(TcpSocket)
}
pub fn bind_exist<A: ToSocketAddrs>(&self, addr: A) -> io::Result<()> {
super::each_addr(addr, |&addr| {
self.0.bind_exist(&addr)
})
}
pub fn accept(&self) -> io::Result<(TcpSocket, SocketAddr)> {
self.0.accept().map(|(a, b)| (TcpSocket(a), b))
}
pub fn incoming(&self) -> Incoming {
Incoming { listener: self }
}
pub fn unlink(self) -> io::Result<()> {
self.0.unlink()
}
pub fn new_v4() -> io::Result<TcpSocket> {
net_imp::TcpSocket::new_v4().map(TcpSocket)
}
pub fn new_v6() -> io::Result<TcpSocket> {
net_imp::TcpSocket::new_v6().map(TcpSocket)
}
pub fn convert_to_stream(self) -> TcpStream {
self.0.convert_to_stream()
}
pub fn convert_to_listener(self) -> TcpListener {
self.0.convert_to_listener()
}
pub fn from_stream(tcp: TcpStream) -> TcpSocket {
TcpSocket(net_imp::TcpSocket::from_stream(tcp))
}
pub fn from_listener(listen: TcpListener) -> TcpSocket {
TcpSocket(net_imp::TcpSocket::from_listener(listen))
}
}
impl Clone for TcpSocket {
fn clone(&self) -> TcpSocket {
TcpSocket(self.0.clone())
}
}
impl Read for TcpSocket {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { self.0.read(buf) }
}
impl Write for TcpSocket {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> { self.0.write(buf) }
fn flush(&mut self) -> io::Result<()> { Ok(()) }
}
impl<'a> Read for &'a TcpSocket {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { self.0.read(buf) }
}
impl<'a> Write for &'a TcpSocket {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> { self.0.write(buf) }
fn flush(&mut self) -> io::Result<()> { Ok(()) }
}
impl AsInner<net_imp::TcpSocket> for TcpSocket {
fn as_inner(&self) -> &net_imp::TcpSocket { &self.0 }
}
impl FromInner<net_imp::TcpSocket> for TcpSocket {
fn from_inner(inner: net_imp::TcpSocket) -> TcpSocket { TcpSocket(inner) }
}
impl IntoInner<net_imp::TcpSocket> for TcpSocket {
fn into_inner(self) -> net_imp::TcpSocket { self.0 }
}
impl fmt::Debug for TcpSocket {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.0.fmt(f)
}
}
impl<'a> Iterator for Incoming<'a> {
type Item = io::Result<TcpSocket>;
fn next(&mut self) -> Option<io::Result<TcpSocket>> {
Some(self.listener.accept().map(|p| p.0))
}
}
#[cfg(all(test, not(target_os = "emscripten")))]
mod tests {
use std::io::ErrorKind;
use std::io::prelude::*;
use net::*;
use std::sync::mpsc::channel;
use sys_common::AsInner;
use std::time::{Instant, Duration};
use std::thread;
use net::test::{next_test_ip4, next_test_ip6};
fn each_ip(f: &mut FnMut(SocketAddr)) {
f(next_test_ip4());
f(next_test_ip6());
}
macro_rules! t {
($e:expr) => {
match $e {
Ok(t) => t,
Err(e) => panic!("received error for `{}`: {}", stringify!($e), e),
}
}
}
#[test]
fn bind_error() {
match TcpSocket::bind("1.1.1.1:9999") {
Ok(..) => panic!(),
Err(e) =>
assert_eq!(e.kind(), ErrorKind::AddrNotAvailable),
}
}
#[test]
fn connect_error() {
match TcpSocket::connect("0.0.0.0:1") {
Ok(..) => panic!(),
Err(e) => assert!(e.kind() == ErrorKind::ConnectionRefused ||
e.kind() == ErrorKind::InvalidInput ||
e.kind() == ErrorKind::AddrInUse ||
e.kind() == ErrorKind::AddrNotAvailable,
"bad error: {} {:?}", e, e.kind()),
}
}
#[test]
fn listen_localhost() {
let socket_addr = next_test_ip4();
let listener = t!(TcpSocket::bind(&socket_addr));
let _t = thread::spawn(move || {
let mut stream = t!(TcpSocket::connect(&("localhost",
socket_addr.port())));
t!(stream.write(&[144]));
});
let mut stream = t!(listener.accept()).0;
let mut buf = [0];
t!(stream.read(&mut buf));
assert!(buf[0] == 144);
}
#[test]
fn connect_loopback() {
each_ip(&mut |addr| {
let acceptor = t!(TcpSocket::bind(&addr));
let _t = thread::spawn(move|| {
let host = match addr {
SocketAddr::V4(..) => "127.0.0.1",
SocketAddr::V6(..) => "::1",
};
let mut stream = t!(TcpSocket::connect(&(host, addr.port())));
t!(stream.write(&[66]));
});
let mut stream = t!(acceptor.accept()).0;
let mut buf = [0];
t!(stream.read(&mut buf));
assert!(buf[0] == 66);
})
}
#[test]
fn smoke_test() {
each_ip(&mut |addr| {
let acceptor = t!(TcpSocket::bind(&addr));
let (tx, rx) = channel();
let _t = thread::spawn(move|| {
let mut stream = t!(TcpSocket::connect(&addr));
t!(stream.write(&[99]));
tx.send(t!(stream.local_addr())).unwrap();
});
let (mut stream, addr) = t!(acceptor.accept());
let mut buf = [0];
t!(stream.read(&mut buf));
assert!(buf[0] == 99);
assert_eq!(addr, t!(rx.recv()));
})
}
#[test]
fn read_eof() {
each_ip(&mut |addr| {
let acceptor = t!(TcpSocket::bind(&addr));
let _t = thread::spawn(move|| {
let _stream = t!(TcpSocket::connect(&addr));
});
let mut stream = t!(acceptor.accept()).0;
let mut buf = [0];
let nread = t!(stream.read(&mut buf));
assert_eq!(nread, 0);
let nread = t!(stream.read(&mut buf));
assert_eq!(nread, 0);
})
}
#[test]
fn write_close() {
each_ip(&mut |addr| {
let acceptor = t!(TcpSocket::bind(&addr));
let (tx, rx) = channel();
let _t = thread::spawn(move|| {
drop(t!(TcpSocket::connect(&addr)));
tx.send(()).unwrap();
});
let mut stream = t!(acceptor.accept()).0;
rx.recv().unwrap();
let buf = [0];
match stream.write(&buf) {
Ok(..) => {}
Err(e) => {
assert!(e.kind() == ErrorKind::ConnectionReset ||
e.kind() == ErrorKind::BrokenPipe ||
e.kind() == ErrorKind::ConnectionAborted,
"unknown error: {}", e);
}
}
})
}
#[test]
fn multiple_connect_serial() {
each_ip(&mut |addr| {
let max = 10;
let acceptor = t!(TcpSocket::bind(&addr));
let _t = thread::spawn(move|| {
for _ in 0..max {
let mut stream = t!(TcpSocket::connect(&addr));
t!(stream.write(&[99]));
}
});
for stream in acceptor.incoming().take(max) {
let mut stream = t!(stream);
let mut buf = [0];
t!(stream.read(&mut buf));
assert_eq!(buf[0], 99);
}
})
}
#[test]
fn multiple_connect_interleaved_greedy_schedule() {
const MAX: usize = 10;
each_ip(&mut |addr| {
let acceptor = t!(TcpSocket::bind(&addr));
let _t = thread::spawn(move|| {
let acceptor = acceptor;
for (i, stream) in acceptor.incoming().enumerate().take(MAX) {
let _t = thread::spawn(move|| {
let mut stream = t!(stream);
let mut buf = [0];
t!(stream.read(&mut buf));
assert!(buf[0] == i as u8);
});
}
});
connect(0, addr);
});
fn connect(i: usize, addr: SocketAddr) {
if i == MAX { return }
let t = thread::spawn(move|| {
let mut stream = t!(TcpSocket::connect(&addr));
connect(i + 1, addr);
t!(stream.write(&[i as u8]));
});
t.join().ok().unwrap();
}
}
#[test]
fn multiple_connect_interleaved_lazy_schedule() {
const MAX: usize = 10;
each_ip(&mut |addr| {
let acceptor = t!(TcpSocket::bind(&addr));
let _t = thread::spawn(move|| {
for stream in acceptor.incoming().take(MAX) {
let _t = thread::spawn(move|| {
let mut stream = t!(stream);
let mut buf = [0];
t!(stream.read(&mut buf));
assert!(buf[0] == 99);
});
}
});
connect(0, addr);
});
fn connect(i: usize, addr: SocketAddr) {
if i == MAX { return }
let t = thread::spawn(move|| {
let mut stream = t!(TcpSocket::connect(&addr));
connect(i + 1, addr);
t!(stream.write(&[99]));
});
t.join().ok().unwrap();
}
}
#[test]
fn socket_and_peer_name() {
each_ip(&mut |addr| {
let listener = t!(TcpSocket::bind(&addr));
let so_name = t!(listener.local_addr());
assert_eq!(addr, so_name);
let _t = thread::spawn(move|| {
t!(listener.accept());
});
let stream = t!(TcpSocket::connect(&addr));
assert_eq!(addr, t!(stream.peer_addr()));
})
}
#[test]
fn partial_read() {
each_ip(&mut |addr| {
let (tx, rx) = channel();
let srv = t!(TcpSocket::bind(&addr));
let _t = thread::spawn(move|| {
let mut cl = t!(srv.accept()).0;
cl.write(&[10]).unwrap();
let mut b = [0];
t!(cl.read(&mut b));
tx.send(()).unwrap();
});
let mut c = t!(TcpSocket::connect(&addr));
let mut b = [0; 10];
assert_eq!(c.read(&mut b).unwrap(), 1);
t!(c.write(&[1]));
rx.recv().unwrap();
})
}
#[test]
fn double_bind() {
each_ip(&mut |addr| {
let _listener = t!(TcpSocket::bind(&addr));
match TcpSocket::bind(&addr) {
Ok(..) => panic!(),
Err(e) => {
assert!(e.kind() == ErrorKind::ConnectionRefused ||
e.kind() == ErrorKind::Other ||
e.kind() == ErrorKind::AddrInUse,
"unknown error: {} {:?}", e, e.kind());
}
}
})
}
#[test]
fn fast_rebind() {
each_ip(&mut |addr| {
let acceptor = t!(TcpSocket::bind(&addr));
let _t = thread::spawn(move|| {
t!(TcpSocket::connect(&addr));
});
t!(acceptor.accept());
drop(acceptor);
t!(TcpSocket::bind(&addr));
});
}
#[test]
fn tcp_clone_smoke() {
each_ip(&mut |addr| {
let acceptor = t!(TcpSocket::bind(&addr));
let _t = thread::spawn(move|| {
let mut s = t!(TcpSocket::connect(&addr));
let mut buf = [0, 0];
assert_eq!(s.read(&mut buf).unwrap(), 1);
assert_eq!(buf[0], 1);
t!(s.write(&[2]));
});
let mut s1 = t!(acceptor.accept()).0;
let s2 = t!(s1.try_clone());
let (tx1, rx1) = channel();
let (tx2, rx2) = channel();
let _t = thread::spawn(move|| {
let mut s2 = s2;
rx1.recv().unwrap();
t!(s2.write(&[1]));
tx2.send(()).unwrap();
});
tx1.send(()).unwrap();
let mut buf = [0, 0];
assert_eq!(s1.read(&mut buf).unwrap(), 1);
rx2.recv().unwrap();
})
}
#[test]
fn tcp_clone_two_read() {
each_ip(&mut |addr| {
let acceptor = t!(TcpSocket::bind(&addr));
let (tx1, rx) = channel();
let tx2 = tx1.clone();
let _t = thread::spawn(move|| {
let mut s = t!(TcpSocket::connect(&addr));
t!(s.write(&[1]));
rx.recv().unwrap();
t!(s.write(&[2]));
rx.recv().unwrap();
});
let mut s1 = t!(acceptor.accept()).0;
let s2 = t!(s1.try_clone());
let (done, rx) = channel();
let _t = thread::spawn(move|| {
let mut s2 = s2;
let mut buf = [0, 0];
t!(s2.read(&mut buf));
tx2.send(()).unwrap();
done.send(()).unwrap();
});
let mut buf = [0, 0];
t!(s1.read(&mut buf));
tx1.send(()).unwrap();
rx.recv().unwrap();
})
}
#[test]
fn tcp_clone_two_write() {
each_ip(&mut |addr| {
let acceptor = t!(TcpSocket::bind(&addr));
let _t = thread::spawn(move|| {
let mut s = t!(TcpSocket::connect(&addr));
let mut buf = [0, 1];
t!(s.read(&mut buf));
t!(s.read(&mut buf));
});
let mut s1 = t!(acceptor.accept()).0;
let s2 = t!(s1.try_clone());
let (done, rx) = channel();
let _t = thread::spawn(move|| {
let mut s2 = s2;
t!(s2.write(&[1]));
done.send(()).unwrap();
});
t!(s1.write(&[2]));
rx.recv().unwrap();
})
}
#[test]
fn shutdown_smoke() {
each_ip(&mut |addr| {
let a = t!(TcpSocket::bind(&addr));
let _t = thread::spawn(move|| {
let mut c = t!(a.accept()).0;
let mut b = [0];
assert_eq!(c.read(&mut b).unwrap(), 0);
t!(c.write(&[1]));
});
let mut s = t!(TcpSocket::connect(&addr));
t!(s.shutdown(Shutdown::Write));
assert!(s.write(&[1]).is_err());
let mut b = [0, 0];
assert_eq!(t!(s.read(&mut b)), 1);
assert_eq!(b[0], 1);
})
}
#[test]
fn close_readwrite_smoke() {
each_ip(&mut |addr| {
let a = t!(TcpSocket::bind(&addr));
let (tx, rx) = channel::<()>();
let _t = thread::spawn(move|| {
let _s = t!(a.accept());
let _ = rx.recv();
});
let mut b = [0];
let mut s = t!(TcpSocket::connect(&addr));
let mut s2 = t!(s.try_clone());
t!(s.shutdown(Shutdown::Write));
assert!(s.write(&[0]).is_err());
t!(s.shutdown(Shutdown::Read));
assert_eq!(s.read(&mut b).unwrap(), 0);
assert!(s2.write(&[0]).is_err());
assert_eq!(s2.read(&mut b).unwrap(), 0);
let mut s3 = t!(s.try_clone());
assert!(s3.write(&[0]).is_err());
assert_eq!(s3.read(&mut b).unwrap(), 0);
let _ = s2.shutdown(Shutdown::Read);
let _ = s2.shutdown(Shutdown::Write);
let _ = s3.shutdown(Shutdown::Read);
let _ = s3.shutdown(Shutdown::Write);
drop(tx);
})
}
#[test]
#[cfg(unix)] fn close_read_wakes_up() {
each_ip(&mut |addr| {
let a = t!(TcpSocket::bind(&addr));
let (tx1, rx) = channel::<()>();
let _t = thread::spawn(move|| {
let _s = t!(a.accept());
let _ = rx.recv();
});
let s = t!(TcpSocket::connect(&addr));
let s2 = t!(s.try_clone());
let (tx, rx) = channel();
let _t = thread::spawn(move|| {
let mut s2 = s2;
assert_eq!(t!(s2.read(&mut [0])), 0);
tx.send(()).unwrap();
});
t!(s.shutdown(Shutdown::Read));
rx.recv().unwrap();
drop(tx1);
})
}
#[test]
fn clone_while_reading() {
each_ip(&mut |addr| {
let accept = t!(TcpSocket::bind(&addr));
let (tx, rx) = channel();
let (txdone, rxdone) = channel();
let txdone2 = txdone.clone();
let _t = thread::spawn(move|| {
let mut tcp = t!(TcpSocket::connect(&addr));
rx.recv().unwrap();
t!(tcp.write(&[0]));
txdone2.send(()).unwrap();
});
let tcp = t!(accept.accept()).0;
let tcp2 = t!(tcp.try_clone());
let txdone3 = txdone.clone();
let _t = thread::spawn(move|| {
println!("tcp2 = {:?}", tcp2);
let mut tcp2 = tcp2;
println!("tcp2 = {:?}", tcp2);
t!(tcp2.read(&mut [0]));
txdone3.send(()).unwrap();
});
for _ in 0..50 {
thread::yield_now();
}
let _ = t!(tcp.try_clone());
tx.send(()).unwrap();
rxdone.recv().unwrap();
rxdone.recv().unwrap();
})
}
#[test]
fn clone_accept_smoke() {
each_ip(&mut |addr| {
let a = t!(TcpSocket::bind(&addr));
let a2 = t!(a.try_clone());
let _t = thread::spawn(move|| {
let _ = TcpSocket::connect(&addr);
});
let _t = thread::spawn(move|| {
let _ = TcpSocket::connect(&addr);
});
t!(a.accept());
t!(a2.accept());
})
}
#[test]
fn clone_accept_concurrent() {
each_ip(&mut |addr| {
let a = t!(TcpSocket::bind(&addr));
let a2 = t!(a.try_clone());
let (tx, rx) = channel();
let tx2 = tx.clone();
let _t = thread::spawn(move|| {
tx.send(t!(a.accept())).unwrap();
});
let _t = thread::spawn(move|| {
tx2.send(t!(a2.accept())).unwrap();
});
let _t = thread::spawn(move|| {
let _ = TcpSocket::connect(&addr);
});
let _t = thread::spawn(move|| {
let _ = TcpSocket::connect(&addr);
});
rx.recv().unwrap();
rx.recv().unwrap();
})
}
#[test]
fn debug() {
let name = if cfg!(windows) {"socket"} else {"fd"};
let socket_addr = next_test_ip4();
let listener = t!(TcpSocket::bind(&socket_addr));
let listener_inner = listener.0.socket().as_inner();
let compare = format!("TcpSocket {{ addr: {:?}, {}: {:?}, ready: {:?} }}",
socket_addr, name, listener_inner, listener.is_ready());
assert_eq!(format!("{:?}", listener), compare);
let stream = t!(TcpSocket::connect(&("localhost",
socket_addr.port())));
let stream_inner = stream.0.socket().as_inner();
let compare = format!("TcpSocket {{ addr: {:?}, \
peer: {:?}, {}: {:?}, ready: {:?} }}",
stream.local_addr().unwrap(),
stream.peer_addr().unwrap(),
name,
stream_inner,
stream.is_ready());
assert_eq!(format!("{:?}", stream), compare);
}
#[cfg_attr(any(target_os = "bitrig", target_os = "netbsd", target_os = "openbsd"), ignore)]
#[test]
fn timeouts() {
let addr = next_test_ip4();
let listener = t!(TcpSocket::bind(&addr));
let stream = t!(TcpSocket::connect(&("localhost", addr.port())));
let dur = Duration::new(15410, 0);
assert_eq!(None, t!(stream.read_timeout()));
t!(stream.set_read_timeout(Some(dur)));
assert_eq!(Some(dur), t!(stream.read_timeout()));
assert_eq!(None, t!(stream.write_timeout()));
t!(stream.set_write_timeout(Some(dur)));
assert_eq!(Some(dur), t!(stream.write_timeout()));
t!(stream.set_read_timeout(None));
assert_eq!(None, t!(stream.read_timeout()));
t!(stream.set_write_timeout(None));
assert_eq!(None, t!(stream.write_timeout()));
drop(listener);
}
#[test]
fn test_read_timeout() {
let addr = next_test_ip4();
let listener = t!(TcpSocket::bind(&addr));
let mut stream = t!(TcpSocket::connect(&("localhost", addr.port())));
t!(stream.set_read_timeout(Some(Duration::from_millis(1000))));
let mut buf = [0; 10];
let start = Instant::now();
let kind = stream.read(&mut buf).err().expect("expected error").kind();
assert!(kind == ErrorKind::WouldBlock || kind == ErrorKind::TimedOut);
assert!(start.elapsed() > Duration::from_millis(400));
drop(listener);
}
#[test]
fn test_read_with_timeout() {
let addr = next_test_ip4();
let listener = t!(TcpSocket::bind(&addr));
let mut stream = t!(TcpSocket::connect(&("localhost", addr.port())));
t!(stream.set_read_timeout(Some(Duration::from_millis(1000))));
let mut other_end = t!(listener.accept()).0;
t!(other_end.write_all(b"hello world"));
let mut buf = [0; 11];
t!(stream.read(&mut buf));
assert_eq!(b"hello world", &buf[..]);
let start = Instant::now();
let kind = stream.read(&mut buf).err().expect("expected error").kind();
assert!(kind == ErrorKind::WouldBlock || kind == ErrorKind::TimedOut);
assert!(start.elapsed() > Duration::from_millis(400));
drop(listener);
}
#[test]
fn nodelay() {
let addr = next_test_ip4();
let _listener = t!(TcpSocket::bind(&addr));
let stream = t!(TcpSocket::connect(&("localhost", addr.port())));
assert_eq!(false, t!(stream.nodelay()));
t!(stream.set_nodelay(true));
assert_eq!(true, t!(stream.nodelay()));
t!(stream.set_nodelay(false));
assert_eq!(false, t!(stream.nodelay()));
}
#[test]
fn ttl() {
let ttl = 100;
let addr = next_test_ip4();
let listener = t!(TcpSocket::bind(&addr));
t!(listener.set_ttl(ttl));
assert_eq!(ttl, t!(listener.ttl()));
let stream = t!(TcpSocket::connect(&("localhost", addr.port())));
t!(stream.set_ttl(ttl));
assert_eq!(ttl, t!(stream.ttl()));
}
#[test]
fn set_nonblocking() {
let addr = next_test_ip4();
let listener = t!(TcpSocket::bind(&addr));
t!(listener.set_nonblocking(true));
t!(listener.set_nonblocking(false));
let mut stream = t!(TcpSocket::connect(&("localhost", addr.port())));
t!(stream.set_nonblocking(false));
t!(stream.set_nonblocking(true));
let mut buf = [0];
match stream.read(&mut buf) {
Ok(_) => panic!("expected error"),
Err(ref e) if e.kind() == ErrorKind::WouldBlock => {}
Err(e) => panic!("unexpected error {}", e),
}
}
#[test]
fn peek() {
each_ip(&mut |addr| {
let (txdone, rxdone) = channel();
let srv = t!(TcpSocket::bind(&addr));
let _t = thread::spawn(move|| {
let mut cl = t!(srv.accept()).0;
cl.write(&[1,3,3,7]).unwrap();
t!(rxdone.recv());
});
let mut c = t!(TcpSocket::connect(&addr));
let mut b = [0; 10];
for _ in 1..3 {
let len = c.peek(&mut b).unwrap();
assert_eq!(len, 4);
}
let len = c.read(&mut b).unwrap();
assert_eq!(len, 4);
t!(c.set_nonblocking(true));
match c.peek(&mut b) {
Ok(_) => panic!("expected error"),
Err(ref e) if e.kind() == ErrorKind::WouldBlock => {}
Err(e) => panic!("unexpected error {}", e),
}
t!(txdone.send(()));
})
}
#[test]
fn connect_timeout_unroutable() {
let addr = "10.255.255.1:80".parse().unwrap();
let e = TcpSocket::connect_timeout(&addr, Duration::from_millis(250)).unwrap_err();
assert!(e.kind() == io::ErrorKind::TimedOut ||
e.kind() == io::ErrorKind::Other,
"bad error: {} {:?}", e, e.kind());
}
#[test]
fn connect_timeout_unbound() {
let socket = TcpSocket::bind("127.0.0.1:2000").unwrap();
let addr = socket.local_addr().unwrap();
drop(socket);
let timeout = Duration::from_secs(1);
let e = TcpSocket::connect_timeout(&addr, timeout).unwrap_err();
assert!(e.kind() == io::ErrorKind::ConnectionRefused ||
e.kind() == io::ErrorKind::TimedOut ||
e.kind() == io::ErrorKind::Other,
"bad error: {} {:?}", e, e.kind());
}
#[test]
fn connect_timeout_valid() {
let listener = TcpSocket::bind("127.0.0.1:2001").unwrap();
let addr = listener.local_addr().unwrap();
TcpSocket::connect_timeout(&addr, Duration::from_secs(2)).unwrap();
}
}