1 // Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 #![unstable(feature = "tcp", reason = "remaining functions have not been \
12 scrutinized enough to be stabilized")]
19 use net::{ToSocketAddrs, SocketAddr, Shutdown};
20 use sys_common::net as net_imp;
21 use sys_common::{AsInner, FromInner};
24 /// A structure which represents a TCP stream between a local socket and a
27 /// The socket will be closed when the value is dropped.
32 /// use std::io::prelude::*;
33 /// use std::net::TcpStream;
36 /// let mut stream = TcpStream::connect("127.0.0.1:34254").unwrap();
38 /// // ignore the Result
39 /// let _ = stream.write(&[1]);
40 /// let _ = stream.read(&mut [0; 128]); // ignore here too
41 /// } // the stream is closed here
43 #[stable(feature = "rust1", since = "1.0.0")]
44 pub struct TcpStream(net_imp::TcpStream);
46 /// A structure representing a socket server.
51 /// use std::net::{TcpListener, TcpStream};
54 /// let listener = TcpListener::bind("127.0.0.1:80").unwrap();
56 /// fn handle_client(stream: TcpStream) {
60 /// // accept connections and process them, spawning a new thread for each one
61 /// for stream in listener.incoming() {
64 /// thread::spawn(move|| {
65 /// // connection succeeded
66 /// handle_client(stream)
69 /// Err(e) => { /* connection failed */ }
73 /// // close the socket server
76 #[stable(feature = "rust1", since = "1.0.0")]
77 pub struct TcpListener(net_imp::TcpListener);
79 /// An infinite iterator over the connections from a `TcpListener`.
81 /// This iterator will infinitely yield `Some` of the accepted connections. It
82 /// is equivalent to calling `accept` in a loop.
83 #[stable(feature = "rust1", since = "1.0.0")]
84 pub struct Incoming<'a> { listener: &'a TcpListener }
87 /// Opens a TCP connection to a remote host.
89 /// `addr` is an address of the remote host. Anything which implements
90 /// `ToSocketAddrs` trait can be supplied for the address; see this trait
91 /// documentation for concrete examples.
92 #[stable(feature = "rust1", since = "1.0.0")]
93 pub fn connect<A: ToSocketAddrs>(addr: A) -> io::Result<TcpStream> {
94 super::each_addr(addr, net_imp::TcpStream::connect).map(TcpStream)
97 /// Returns the socket address of the remote peer of this TCP connection.
98 #[stable(feature = "rust1", since = "1.0.0")]
99 pub fn peer_addr(&self) -> io::Result<SocketAddr> {
103 /// Returns the socket address of the local half of this TCP connection.
104 #[stable(feature = "rust1", since = "1.0.0")]
105 pub fn local_addr(&self) -> io::Result<SocketAddr> {
109 /// Shuts down the read, write, or both halves of this connection.
111 /// This function will cause all pending and future I/O on the specified
112 /// portions to return immediately with an appropriate value (see the
113 /// documentation of `Shutdown`).
114 #[stable(feature = "rust1", since = "1.0.0")]
115 pub fn shutdown(&self, how: Shutdown) -> io::Result<()> {
119 /// Creates a new independently owned handle to the underlying socket.
121 /// The returned `TcpStream` is a reference to the same stream that this
122 /// object references. Both handles will read and write the same stream of
123 /// data, and options set on one stream will be propagated to the other
125 #[stable(feature = "rust1", since = "1.0.0")]
126 pub fn try_clone(&self) -> io::Result<TcpStream> {
127 self.0.duplicate().map(TcpStream)
130 /// Sets the nodelay flag on this connection to the boolean specified.
131 pub fn set_nodelay(&self, nodelay: bool) -> io::Result<()> {
132 self.0.set_nodelay(nodelay)
135 /// Sets the keepalive timeout to the timeout specified.
137 /// If the value specified is `None`, then the keepalive flag is cleared on
138 /// this connection. Otherwise, the keepalive timeout will be set to the
139 /// specified time, in seconds.
140 pub fn set_keepalive(&self, seconds: Option<u32>) -> io::Result<()> {
141 self.0.set_keepalive(seconds)
144 /// Sets the read timeout to the timeout specified.
146 /// If the value specified is `None`, then `read` calls will block
147 /// indefinitely. It is an error to pass the zero `Duration` to this
149 #[unstable(feature = "socket_timeout", reason = "RFC 1047 - recently added")]
150 pub fn set_read_timeout(&self, dur: Option<Duration>) -> io::Result<()> {
151 self.0.set_read_timeout(dur)
154 /// Sets the write timeout to the timeout specified.
156 /// If the value specified is `None`, then `write` calls will block
157 /// indefinitely. It is an error to pass the zero `Duration` to this
159 #[unstable(feature = "socket_timeout", reason = "RFC 1047 - recently added")]
160 pub fn set_write_timeout(&self, dur: Option<Duration>) -> io::Result<()> {
161 self.0.set_write_timeout(dur)
164 /// Returns the read timeout of this socket.
166 /// If the timeout is `None`, then `read` calls will block indefinitely.
170 /// Some platforms do not provide access to the current timeout.
171 #[unstable(feature = "socket_timeout", reason = "RFC 1047 - recently added")]
172 pub fn read_timeout(&self) -> io::Result<Option<Duration>> {
173 self.0.read_timeout()
176 /// Returns the write timeout of this socket.
178 /// If the timeout is `None`, then `write` calls will block indefinitely.
182 /// Some platforms do not provide access to the current timeout.
183 #[unstable(feature = "socket_timeout", reason = "RFC 1047 - recently added")]
184 pub fn write_timeout(&self) -> io::Result<Option<Duration>> {
185 self.0.write_timeout()
189 #[stable(feature = "rust1", since = "1.0.0")]
190 impl Read for TcpStream {
191 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { self.0.read(buf) }
193 #[stable(feature = "rust1", since = "1.0.0")]
194 impl Write for TcpStream {
195 fn write(&mut self, buf: &[u8]) -> io::Result<usize> { self.0.write(buf) }
196 fn flush(&mut self) -> io::Result<()> { Ok(()) }
198 #[stable(feature = "rust1", since = "1.0.0")]
199 impl<'a> Read for &'a TcpStream {
200 fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { self.0.read(buf) }
202 #[stable(feature = "rust1", since = "1.0.0")]
203 impl<'a> Write for &'a TcpStream {
204 fn write(&mut self, buf: &[u8]) -> io::Result<usize> { self.0.write(buf) }
205 fn flush(&mut self) -> io::Result<()> { Ok(()) }
208 impl AsInner<net_imp::TcpStream> for TcpStream {
209 fn as_inner(&self) -> &net_imp::TcpStream { &self.0 }
212 impl FromInner<net_imp::TcpStream> for TcpStream {
213 fn from_inner(inner: net_imp::TcpStream) -> TcpStream { TcpStream(inner) }
216 impl fmt::Debug for TcpStream {
217 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
223 /// Creates a new `TcpListener` which will be bound to the specified
226 /// The returned listener is ready for accepting connections.
228 /// Binding with a port number of 0 will request that the OS assigns a port
229 /// to this listener. The port allocated can be queried via the
230 /// `socket_addr` function.
232 /// The address type can be any implementer of `ToSocketAddrs` trait. See
233 /// its documentation for concrete examples.
234 #[stable(feature = "rust1", since = "1.0.0")]
235 pub fn bind<A: ToSocketAddrs>(addr: A) -> io::Result<TcpListener> {
236 super::each_addr(addr, net_imp::TcpListener::bind).map(TcpListener)
239 /// Returns the local socket address of this listener.
240 #[stable(feature = "rust1", since = "1.0.0")]
241 pub fn local_addr(&self) -> io::Result<SocketAddr> {
245 /// Creates a new independently owned handle to the underlying socket.
247 /// The returned `TcpListener` is a reference to the same socket that this
248 /// object references. Both handles can be used to accept incoming
249 /// connections and options set on one listener will affect the other.
250 #[stable(feature = "rust1", since = "1.0.0")]
251 pub fn try_clone(&self) -> io::Result<TcpListener> {
252 self.0.duplicate().map(TcpListener)
255 /// Accept a new incoming connection from this listener.
257 /// This function will block the calling thread until a new TCP connection
258 /// is established. When established, the corresponding `TcpStream` and the
259 /// remote peer's address will be returned.
260 #[stable(feature = "rust1", since = "1.0.0")]
261 pub fn accept(&self) -> io::Result<(TcpStream, SocketAddr)> {
262 self.0.accept().map(|(a, b)| (TcpStream(a), b))
265 /// Returns an iterator over the connections being received on this
268 /// The returned iterator will never return `None` and will also not yield
269 /// the peer's `SocketAddr` structure.
270 #[stable(feature = "rust1", since = "1.0.0")]
271 pub fn incoming(&self) -> Incoming {
272 Incoming { listener: self }
276 #[stable(feature = "rust1", since = "1.0.0")]
277 impl<'a> Iterator for Incoming<'a> {
278 type Item = io::Result<TcpStream>;
279 fn next(&mut self) -> Option<io::Result<TcpStream>> {
280 Some(self.listener.accept().map(|p| p.0))
284 impl AsInner<net_imp::TcpListener> for TcpListener {
285 fn as_inner(&self) -> &net_imp::TcpListener { &self.0 }
288 impl FromInner<net_imp::TcpListener> for TcpListener {
289 fn from_inner(inner: net_imp::TcpListener) -> TcpListener {
294 impl fmt::Debug for TcpListener {
295 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
307 use net::test::{next_test_ip4, next_test_ip6};
308 use sync::mpsc::channel;
309 use sys_common::AsInner;
313 fn each_ip(f: &mut FnMut(SocketAddr)) {
322 Err(e) => panic!("received error for `{}`: {}", stringify!($e), e),
329 match TcpListener::bind("1.1.1.1:9999") {
332 assert_eq!(e.kind(), ErrorKind::AddrNotAvailable),
338 match TcpStream::connect("0.0.0.0:1") {
340 Err(e) => assert!(e.kind() == ErrorKind::ConnectionRefused ||
341 e.kind() == ErrorKind::InvalidInput ||
342 e.kind() == ErrorKind::AddrInUse ||
343 e.kind() == ErrorKind::AddrNotAvailable,
344 "bad error: {} {:?}", e, e.kind()),
349 fn listen_localhost() {
350 let socket_addr = next_test_ip4();
351 let listener = t!(TcpListener::bind(&socket_addr));
353 let _t = thread::spawn(move || {
354 let mut stream = t!(TcpStream::connect(&("localhost",
355 socket_addr.port())));
356 t!(stream.write(&[144]));
359 let mut stream = t!(listener.accept()).0;
361 t!(stream.read(&mut buf));
362 assert!(buf[0] == 144);
366 fn connect_ip4_loopback() {
367 let addr = next_test_ip4();
368 let acceptor = t!(TcpListener::bind(&addr));
370 let _t = thread::spawn(move|| {
371 let mut stream = t!(TcpStream::connect(&("127.0.0.1", addr.port())));
372 t!(stream.write(&[44]));
375 let mut stream = t!(acceptor.accept()).0;
377 t!(stream.read(&mut buf));
378 assert!(buf[0] == 44);
382 fn connect_ip6_loopback() {
383 let addr = next_test_ip6();
384 let acceptor = t!(TcpListener::bind(&addr));
386 let _t = thread::spawn(move|| {
387 let mut stream = t!(TcpStream::connect(&("::1", addr.port())));
388 t!(stream.write(&[66]));
391 let mut stream = t!(acceptor.accept()).0;
393 t!(stream.read(&mut buf));
394 assert!(buf[0] == 66);
398 fn smoke_test_ip6() {
399 each_ip(&mut |addr| {
400 let acceptor = t!(TcpListener::bind(&addr));
402 let (tx, rx) = channel();
403 let _t = thread::spawn(move|| {
404 let mut stream = t!(TcpStream::connect(&addr));
405 t!(stream.write(&[99]));
406 tx.send(t!(stream.local_addr())).unwrap();
409 let (mut stream, addr) = t!(acceptor.accept());
411 t!(stream.read(&mut buf));
412 assert!(buf[0] == 99);
413 assert_eq!(addr, t!(rx.recv()));
419 each_ip(&mut |addr| {
420 let acceptor = t!(TcpListener::bind(&addr));
422 let _t = thread::spawn(move|| {
423 let _stream = t!(TcpStream::connect(&addr));
427 let mut stream = t!(acceptor.accept()).0;
429 let nread = t!(stream.read(&mut buf));
430 assert_eq!(nread, 0);
431 let nread = t!(stream.read(&mut buf));
432 assert_eq!(nread, 0);
438 each_ip(&mut |addr| {
439 let acceptor = t!(TcpListener::bind(&addr));
441 let (tx, rx) = channel();
442 let _t = thread::spawn(move|| {
443 drop(t!(TcpStream::connect(&addr)));
444 tx.send(()).unwrap();
447 let mut stream = t!(acceptor.accept()).0;
450 match stream.write(&buf) {
453 assert!(e.kind() == ErrorKind::ConnectionReset ||
454 e.kind() == ErrorKind::BrokenPipe ||
455 e.kind() == ErrorKind::ConnectionAborted,
456 "unknown error: {}", e);
463 fn multiple_connect_serial_ip4() {
464 each_ip(&mut |addr| {
466 let acceptor = t!(TcpListener::bind(&addr));
468 let _t = thread::spawn(move|| {
470 let mut stream = t!(TcpStream::connect(&addr));
471 t!(stream.write(&[99]));
475 for stream in acceptor.incoming().take(max) {
476 let mut stream = t!(stream);
478 t!(stream.read(&mut buf));
479 assert_eq!(buf[0], 99);
485 fn multiple_connect_interleaved_greedy_schedule() {
486 const MAX: usize = 10;
487 each_ip(&mut |addr| {
488 let acceptor = t!(TcpListener::bind(&addr));
490 let _t = thread::spawn(move|| {
491 let acceptor = acceptor;
492 for (i, stream) in acceptor.incoming().enumerate().take(MAX) {
493 // Start another thread to handle the connection
494 let _t = thread::spawn(move|| {
495 let mut stream = t!(stream);
497 t!(stream.read(&mut buf));
498 assert!(buf[0] == i as u8);
506 fn connect(i: usize, addr: SocketAddr) {
507 if i == MAX { return }
509 let t = thread::spawn(move|| {
510 let mut stream = t!(TcpStream::connect(&addr));
511 // Connect again before writing
512 connect(i + 1, addr);
513 t!(stream.write(&[i as u8]));
515 t.join().ok().unwrap();
520 fn multiple_connect_interleaved_lazy_schedule_ip4() {
521 const MAX: usize = 10;
522 each_ip(&mut |addr| {
523 let acceptor = t!(TcpListener::bind(&addr));
525 let _t = thread::spawn(move|| {
526 for stream in acceptor.incoming().take(MAX) {
527 // Start another thread to handle the connection
528 let _t = thread::spawn(move|| {
529 let mut stream = t!(stream);
531 t!(stream.read(&mut buf));
532 assert!(buf[0] == 99);
540 fn connect(i: usize, addr: SocketAddr) {
541 if i == MAX { return }
543 let t = thread::spawn(move|| {
544 let mut stream = t!(TcpStream::connect(&addr));
545 connect(i + 1, addr);
546 t!(stream.write(&[99]));
548 t.join().ok().unwrap();
553 fn socket_and_peer_name_ip4() {
554 each_ip(&mut |addr| {
555 let listener = t!(TcpListener::bind(&addr));
556 let so_name = t!(listener.local_addr());
557 assert_eq!(addr, so_name);
558 let _t = thread::spawn(move|| {
559 t!(listener.accept());
562 let stream = t!(TcpStream::connect(&addr));
563 assert_eq!(addr, t!(stream.peer_addr()));
569 each_ip(&mut |addr| {
570 let (tx, rx) = channel();
571 let srv = t!(TcpListener::bind(&addr));
572 let _t = thread::spawn(move|| {
573 let mut cl = t!(srv.accept()).0;
574 cl.write(&[10]).unwrap();
577 tx.send(()).unwrap();
580 let mut c = t!(TcpStream::connect(&addr));
582 assert_eq!(c.read(&mut b).unwrap(), 1);
590 each_ip(&mut |addr| {
591 let _listener = t!(TcpListener::bind(&addr));
592 match TcpListener::bind(&addr) {
595 assert!(e.kind() == ErrorKind::ConnectionRefused ||
596 e.kind() == ErrorKind::Other ||
597 e.kind() == ErrorKind::AddrInUse,
598 "unknown error: {} {:?}", e, e.kind());
606 each_ip(&mut |addr| {
607 let acceptor = t!(TcpListener::bind(&addr));
609 let _t = thread::spawn(move|| {
610 t!(TcpStream::connect(&addr));
613 t!(acceptor.accept());
615 t!(TcpListener::bind(&addr));
620 fn tcp_clone_smoke() {
621 each_ip(&mut |addr| {
622 let acceptor = t!(TcpListener::bind(&addr));
624 let _t = thread::spawn(move|| {
625 let mut s = t!(TcpStream::connect(&addr));
626 let mut buf = [0, 0];
627 assert_eq!(s.read(&mut buf).unwrap(), 1);
628 assert_eq!(buf[0], 1);
632 let mut s1 = t!(acceptor.accept()).0;
633 let s2 = t!(s1.try_clone());
635 let (tx1, rx1) = channel();
636 let (tx2, rx2) = channel();
637 let _t = thread::spawn(move|| {
641 tx2.send(()).unwrap();
643 tx1.send(()).unwrap();
644 let mut buf = [0, 0];
645 assert_eq!(s1.read(&mut buf).unwrap(), 1);
651 fn tcp_clone_two_read() {
652 each_ip(&mut |addr| {
653 let acceptor = t!(TcpListener::bind(&addr));
654 let (tx1, rx) = channel();
655 let tx2 = tx1.clone();
657 let _t = thread::spawn(move|| {
658 let mut s = t!(TcpStream::connect(&addr));
665 let mut s1 = t!(acceptor.accept()).0;
666 let s2 = t!(s1.try_clone());
668 let (done, rx) = channel();
669 let _t = thread::spawn(move|| {
671 let mut buf = [0, 0];
672 t!(s2.read(&mut buf));
673 tx2.send(()).unwrap();
674 done.send(()).unwrap();
676 let mut buf = [0, 0];
677 t!(s1.read(&mut buf));
678 tx1.send(()).unwrap();
685 fn tcp_clone_two_write() {
686 each_ip(&mut |addr| {
687 let acceptor = t!(TcpListener::bind(&addr));
689 let _t = thread::spawn(move|| {
690 let mut s = t!(TcpStream::connect(&addr));
691 let mut buf = [0, 1];
692 t!(s.read(&mut buf));
693 t!(s.read(&mut buf));
696 let mut s1 = t!(acceptor.accept()).0;
697 let s2 = t!(s1.try_clone());
699 let (done, rx) = channel();
700 let _t = thread::spawn(move|| {
703 done.send(()).unwrap();
712 fn shutdown_smoke() {
713 each_ip(&mut |addr| {
714 let a = t!(TcpListener::bind(&addr));
715 let _t = thread::spawn(move|| {
716 let mut c = t!(a.accept()).0;
718 assert_eq!(c.read(&mut b).unwrap(), 0);
722 let mut s = t!(TcpStream::connect(&addr));
723 t!(s.shutdown(Shutdown::Write));
724 assert!(s.write(&[1]).is_err());
726 assert_eq!(t!(s.read(&mut b)), 1);
732 fn close_readwrite_smoke() {
733 each_ip(&mut |addr| {
734 let a = t!(TcpListener::bind(&addr));
735 let (tx, rx) = channel::<()>();
736 let _t = thread::spawn(move|| {
737 let _s = t!(a.accept());
742 let mut s = t!(TcpStream::connect(&addr));
743 let mut s2 = t!(s.try_clone());
745 // closing should prevent reads/writes
746 t!(s.shutdown(Shutdown::Write));
747 assert!(s.write(&[0]).is_err());
748 t!(s.shutdown(Shutdown::Read));
749 assert_eq!(s.read(&mut b).unwrap(), 0);
751 // closing should affect previous handles
752 assert!(s2.write(&[0]).is_err());
753 assert_eq!(s2.read(&mut b).unwrap(), 0);
755 // closing should affect new handles
756 let mut s3 = t!(s.try_clone());
757 assert!(s3.write(&[0]).is_err());
758 assert_eq!(s3.read(&mut b).unwrap(), 0);
760 // make sure these don't die
761 let _ = s2.shutdown(Shutdown::Read);
762 let _ = s2.shutdown(Shutdown::Write);
763 let _ = s3.shutdown(Shutdown::Read);
764 let _ = s3.shutdown(Shutdown::Write);
770 fn close_read_wakes_up() {
771 each_ip(&mut |addr| {
772 let a = t!(TcpListener::bind(&addr));
773 let (tx1, rx) = channel::<()>();
774 let _t = thread::spawn(move|| {
775 let _s = t!(a.accept());
779 let s = t!(TcpStream::connect(&addr));
780 let s2 = t!(s.try_clone());
781 let (tx, rx) = channel();
782 let _t = thread::spawn(move|| {
784 assert_eq!(t!(s2.read(&mut [0])), 0);
785 tx.send(()).unwrap();
787 // this should wake up the child thread
788 t!(s.shutdown(Shutdown::Read));
790 // this test will never finish if the child doesn't wake up
797 fn clone_while_reading() {
798 each_ip(&mut |addr| {
799 let accept = t!(TcpListener::bind(&addr));
801 // Enqueue a thread to write to a socket
802 let (tx, rx) = channel();
803 let (txdone, rxdone) = channel();
804 let txdone2 = txdone.clone();
805 let _t = thread::spawn(move|| {
806 let mut tcp = t!(TcpStream::connect(&addr));
809 txdone2.send(()).unwrap();
812 // Spawn off a reading clone
813 let tcp = t!(accept.accept()).0;
814 let tcp2 = t!(tcp.try_clone());
815 let txdone3 = txdone.clone();
816 let _t = thread::spawn(move|| {
818 t!(tcp2.read(&mut [0]));
819 txdone3.send(()).unwrap();
822 // Try to ensure that the reading clone is indeed reading
827 // clone the handle again while it's reading, then let it finish the
829 let _ = t!(tcp.try_clone());
830 tx.send(()).unwrap();
831 rxdone.recv().unwrap();
832 rxdone.recv().unwrap();
837 fn clone_accept_smoke() {
838 each_ip(&mut |addr| {
839 let a = t!(TcpListener::bind(&addr));
840 let a2 = t!(a.try_clone());
842 let _t = thread::spawn(move|| {
843 let _ = TcpStream::connect(&addr);
845 let _t = thread::spawn(move|| {
846 let _ = TcpStream::connect(&addr);
855 fn clone_accept_concurrent() {
856 each_ip(&mut |addr| {
857 let a = t!(TcpListener::bind(&addr));
858 let a2 = t!(a.try_clone());
860 let (tx, rx) = channel();
861 let tx2 = tx.clone();
863 let _t = thread::spawn(move|| {
864 tx.send(t!(a.accept())).unwrap();
866 let _t = thread::spawn(move|| {
867 tx2.send(t!(a2.accept())).unwrap();
870 let _t = thread::spawn(move|| {
871 let _ = TcpStream::connect(&addr);
873 let _t = thread::spawn(move|| {
874 let _ = TcpStream::connect(&addr);
884 let name = if cfg!(windows) {"socket"} else {"fd"};
885 let socket_addr = next_test_ip4();
887 let listener = t!(TcpListener::bind(&socket_addr));
888 let listener_inner = listener.0.socket().as_inner();
889 let compare = format!("TcpListener {{ addr: {:?}, {}: {:?} }}",
890 socket_addr, name, listener_inner);
891 assert_eq!(format!("{:?}", listener), compare);
893 let stream = t!(TcpStream::connect(&("localhost",
894 socket_addr.port())));
895 let stream_inner = stream.0.socket().as_inner();
896 let compare = format!("TcpStream {{ addr: {:?}, \
897 peer: {:?}, {}: {:?} }}",
898 stream.local_addr().unwrap(),
899 stream.peer_addr().unwrap(),
902 assert_eq!(format!("{:?}", stream), compare);
905 // FIXME: re-enabled bitrig/openbsd tests once their socket timeout code
906 // no longer has rounding errors.
907 #[cfg_attr(any(target_os = "bitrig", target_os = "openbsd"), ignore)]
910 let addr = next_test_ip4();
911 let listener = t!(TcpListener::bind(&addr));
913 let stream = t!(TcpStream::connect(&("localhost", addr.port())));
914 let dur = Duration::new(15410, 0);
916 assert_eq!(None, t!(stream.read_timeout()));
918 t!(stream.set_read_timeout(Some(dur)));
919 assert_eq!(Some(dur), t!(stream.read_timeout()));
921 assert_eq!(None, t!(stream.write_timeout()));
923 t!(stream.set_write_timeout(Some(dur)));
924 assert_eq!(Some(dur), t!(stream.write_timeout()));
926 t!(stream.set_read_timeout(None));
927 assert_eq!(None, t!(stream.read_timeout()));
929 t!(stream.set_write_timeout(None));
930 assert_eq!(None, t!(stream.write_timeout()));
934 fn test_read_timeout() {
935 let addr = next_test_ip4();
936 let listener = t!(TcpListener::bind(&addr));
938 let mut stream = t!(TcpStream::connect(&("localhost", addr.port())));
939 t!(stream.set_read_timeout(Some(Duration::from_millis(1000))));
941 let mut buf = [0; 10];
942 let wait = Duration::span(|| {
943 let kind = stream.read(&mut buf).err().expect("expected error").kind();
944 assert!(kind == ErrorKind::WouldBlock || kind == ErrorKind::TimedOut);
946 assert!(wait > Duration::from_millis(400));
947 assert!(wait < Duration::from_millis(1600));
951 fn test_read_with_timeout() {
952 let addr = next_test_ip4();
953 let listener = t!(TcpListener::bind(&addr));
955 let mut stream = t!(TcpStream::connect(&("localhost", addr.port())));
956 t!(stream.set_read_timeout(Some(Duration::from_millis(1000))));
958 let mut other_end = t!(listener.accept()).0;
959 t!(other_end.write_all(b"hello world"));
961 let mut buf = [0; 11];
962 t!(stream.read(&mut buf));
963 assert_eq!(b"hello world", &buf[..]);
965 let wait = Duration::span(|| {
966 let kind = stream.read(&mut buf).err().expect("expected error").kind();
967 assert!(kind == ErrorKind::WouldBlock || kind == ErrorKind::TimedOut);
969 assert!(wait > Duration::from_millis(400));
970 assert!(wait < Duration::from_millis(1600));