tokio/net/tcp/stream.rs
1cfg_not_wasi! {
2 use std::time::Duration;
3}
4
5cfg_not_wasip1! {
6 use crate::net::{to_socket_addrs, ToSocketAddrs};
7 use std::future::poll_fn;
8}
9
10use crate::io::{AsyncRead, AsyncWrite, Interest, PollEvented, ReadBuf, Ready};
11use crate::net::tcp::split::{split, ReadHalf, WriteHalf};
12use crate::net::tcp::split_owned::{split_owned, OwnedReadHalf, OwnedWriteHalf};
13use crate::util::check_socket_for_blocking;
14
15use std::fmt;
16use std::io;
17use std::net::{Shutdown, SocketAddr};
18use std::pin::Pin;
19use std::task::{ready, Context, Poll};
20
21cfg_io_util! {
22 use bytes::BufMut;
23}
24
25cfg_net! {
26 /// A TCP stream between a local and a remote socket.
27 ///
28 /// A TCP stream can either be created by connecting to an endpoint, via the
29 /// [`connect`] method, or by [accepting] a connection from a [listener]. A
30 /// TCP stream can also be created via the [`TcpSocket`] type.
31 ///
32 /// Reading and writing to a `TcpStream` is usually done using the
33 /// convenience methods found on the [`AsyncReadExt`] and [`AsyncWriteExt`]
34 /// traits.
35 ///
36 /// [`connect`]: method@TcpStream::connect
37 /// [accepting]: method@crate::net::TcpListener::accept
38 /// [listener]: struct@crate::net::TcpListener
39 /// [`TcpSocket`]: struct@crate::net::TcpSocket
40 /// [`AsyncReadExt`]: trait@crate::io::AsyncReadExt
41 /// [`AsyncWriteExt`]: trait@crate::io::AsyncWriteExt
42 ///
43 /// # Examples
44 ///
45 /// ```no_run
46 /// use tokio::net::TcpStream;
47 /// use tokio::io::AsyncWriteExt;
48 /// use std::error::Error;
49 ///
50 /// #[tokio::main]
51 /// async fn main() -> Result<(), Box<dyn Error>> {
52 /// // Connect to a peer
53 /// let mut stream = TcpStream::connect("127.0.0.1:8080").await?;
54 ///
55 /// // Write some data.
56 /// stream.write_all(b"hello world!").await?;
57 ///
58 /// Ok(())
59 /// }
60 /// ```
61 ///
62 /// The [`write_all`] method is defined on the [`AsyncWriteExt`] trait.
63 ///
64 /// [`write_all`]: fn@crate::io::AsyncWriteExt::write_all
65 /// [`AsyncWriteExt`]: trait@crate::io::AsyncWriteExt
66 ///
67 /// To shut down the stream in the write direction, you can call the
68 /// [`shutdown()`] method. This will cause the other peer to receive a read of
69 /// length 0, indicating that no more data will be sent. This only closes
70 /// the stream in one direction.
71 ///
72 /// [`shutdown()`]: fn@crate::io::AsyncWriteExt::shutdown
73 pub struct TcpStream {
74 io: PollEvented<mio::net::TcpStream>,
75 }
76}
77
78impl TcpStream {
79 cfg_not_wasip1! {
80 /// Opens a TCP connection to a remote host.
81 ///
82 /// `addr` is an address of the remote host. Anything which implements the
83 /// [`ToSocketAddrs`] trait can be supplied as the address. If `addr`
84 /// yields multiple addresses, connect will be attempted with each of the
85 /// addresses until a connection is successful. If none of the addresses
86 /// result in a successful connection, the error returned from the last
87 /// connection attempt (the last address) is returned.
88 ///
89 /// For example, on a host without IPv6 connectivity, the
90 /// `AddrNotAvailable` error of a later IPv6 attempt can hide an earlier
91 /// IPv4 failure such as connection refused.
92 /// To configure the socket before connecting, you can use the [`TcpSocket`]
93 /// type.
94 ///
95 /// [`ToSocketAddrs`]: trait@crate::net::ToSocketAddrs
96 /// [`TcpSocket`]: struct@crate::net::TcpSocket
97 ///
98 /// # Examples
99 ///
100 /// ```no_run
101 /// use tokio::net::TcpStream;
102 /// use tokio::io::AsyncWriteExt;
103 /// use std::error::Error;
104 ///
105 /// #[tokio::main]
106 /// async fn main() -> Result<(), Box<dyn Error>> {
107 /// // Connect to a peer
108 /// let mut stream = TcpStream::connect("127.0.0.1:8080").await?;
109 ///
110 /// // Write some data.
111 /// stream.write_all(b"hello world!").await?;
112 ///
113 /// Ok(())
114 /// }
115 /// ```
116 ///
117 /// The [`write_all`] method is defined on the [`AsyncWriteExt`] trait.
118 ///
119 /// [`write_all`]: fn@crate::io::AsyncWriteExt::write_all
120 /// [`AsyncWriteExt`]: trait@crate::io::AsyncWriteExt
121 pub async fn connect<A: ToSocketAddrs>(addr: A) -> io::Result<TcpStream> {
122 let addrs = to_socket_addrs(addr).await?;
123
124 let mut last_err = None;
125
126 for addr in addrs {
127 match TcpStream::connect_addr(addr).await {
128 Ok(stream) => return Ok(stream),
129 Err(e) => last_err = Some(e),
130 }
131 }
132
133 Err(last_err.unwrap_or_else(|| {
134 io::Error::new(
135 io::ErrorKind::InvalidInput,
136 "could not resolve to any address",
137 )
138 }))
139 }
140
141 /// Establishes a connection to the specified `addr`.
142 async fn connect_addr(addr: SocketAddr) -> io::Result<TcpStream> {
143 let sys = mio::net::TcpStream::connect(addr)?;
144 TcpStream::connect_mio(sys).await
145 }
146
147 pub(crate) async fn connect_mio(sys: mio::net::TcpStream) -> io::Result<TcpStream> {
148 let stream = TcpStream::new(sys)?;
149
150 // Once we've connected, wait for the stream to be writable as
151 // that's when the actual connection has been initiated. Once we're
152 // writable we check for `take_socket_error` to see if the connect
153 // actually hit an error or not.
154 //
155 // If all that succeeded then we ship everything on up.
156 poll_fn(|cx| stream.io.registration().poll_write_ready(cx)).await?;
157
158 if let Some(e) = stream.io.take_error()? {
159 return Err(e);
160 }
161
162 Ok(stream)
163 }
164 }
165
166 pub(crate) fn new(connected: mio::net::TcpStream) -> io::Result<TcpStream> {
167 let io = PollEvented::new(connected)?;
168 Ok(TcpStream { io })
169 }
170
171 /// A stream returned by `accept`: assumed readable and writable, so that
172 /// its first read and write try the socket instead of waiting for the
173 /// driver's first event (see `Registration::assume_ready`).
174 pub(crate) fn new_accepted(connected: mio::net::TcpStream) -> io::Result<TcpStream> {
175 let stream = TcpStream::new(connected)?;
176 stream
177 .io
178 .registration()
179 .assume_ready(Ready::READABLE | Ready::WRITABLE);
180 Ok(stream)
181 }
182
183 /// Creates new `TcpStream` from a `std::net::TcpStream`.
184 ///
185 /// This function is intended to be used to wrap a TCP stream from the
186 /// standard library in the Tokio equivalent.
187 ///
188 /// # Notes
189 ///
190 /// The caller is responsible for ensuring that the stream is in
191 /// non-blocking mode. Otherwise all I/O operations on the stream
192 /// will block the thread, which will cause unexpected behavior.
193 /// Non-blocking mode can be set using [`set_nonblocking`].
194 ///
195 /// Passing a listener in blocking mode is always erroneous,
196 /// and the behavior in that case may change in the future.
197 /// For example, it could panic.
198 ///
199 /// [`set_nonblocking`]: std::net::TcpStream::set_nonblocking
200 ///
201 /// # Examples
202 ///
203 /// ```rust,no_run
204 /// use std::error::Error;
205 /// use tokio::net::TcpStream;
206 ///
207 /// #[tokio::main]
208 /// async fn main() -> Result<(), Box<dyn Error>> {
209 /// let std_stream = std::net::TcpStream::connect("127.0.0.1:34254")?;
210 /// std_stream.set_nonblocking(true)?;
211 /// let stream = TcpStream::from_std(std_stream)?;
212 /// Ok(())
213 /// }
214 /// ```
215 ///
216 /// # Panics
217 ///
218 /// This function panics if it is not called from within a runtime with
219 /// IO enabled.
220 ///
221 /// The runtime is usually set implicitly when this function is called
222 /// from a future driven by a tokio runtime, otherwise runtime can be set
223 /// explicitly with [`Runtime::enter`](crate::runtime::Runtime::enter) function.
224 #[track_caller]
225 pub fn from_std(stream: std::net::TcpStream) -> io::Result<TcpStream> {
226 check_socket_for_blocking(&stream)?;
227
228 let io = mio::net::TcpStream::from_std(stream);
229 let io = PollEvented::new(io)?;
230 Ok(TcpStream { io })
231 }
232
233 /// Turns a [`tokio::net::TcpStream`] into a [`std::net::TcpStream`].
234 ///
235 /// The returned [`std::net::TcpStream`] will have nonblocking mode set as `true`.
236 /// Use [`set_nonblocking`] to change the blocking mode if needed.
237 ///
238 /// # Examples
239 ///
240 /// ```
241 /// use std::error::Error;
242 /// use std::io::Read;
243 /// use tokio::net::TcpListener;
244 /// # use tokio::net::TcpStream;
245 /// # use tokio::io::AsyncWriteExt;
246 ///
247 /// #[tokio::main]
248 /// async fn main() -> Result<(), Box<dyn Error>> {
249 /// let mut data = [0u8; 12];
250 /// # if false {
251 /// let listener = TcpListener::bind("127.0.0.1:34254").await?;
252 /// # }
253 /// # let listener = TcpListener::bind("127.0.0.1:0").await?;
254 /// # let addr = listener.local_addr().unwrap();
255 /// # let handle = tokio::spawn(async move {
256 /// # let mut stream: TcpStream = TcpStream::connect(addr).await.unwrap();
257 /// # stream.write_all(b"Hello world!").await.unwrap();
258 /// # });
259 /// let (tokio_tcp_stream, _) = listener.accept().await?;
260 /// let mut std_tcp_stream = tokio_tcp_stream.into_std()?;
261 /// # handle.await.expect("The task being joined has panicked");
262 /// std_tcp_stream.set_nonblocking(false)?;
263 /// std_tcp_stream.read_exact(&mut data)?;
264 /// # assert_eq!(b"Hello world!", &data);
265 /// Ok(())
266 /// }
267 /// ```
268 /// [`tokio::net::TcpStream`]: TcpStream
269 /// [`std::net::TcpStream`]: std::net::TcpStream
270 /// [`set_nonblocking`]: fn@std::net::TcpStream::set_nonblocking
271 pub fn into_std(self) -> io::Result<std::net::TcpStream> {
272 #[cfg(unix)]
273 {
274 use std::os::unix::io::{FromRawFd, IntoRawFd};
275 self.io
276 .into_inner()
277 .map(IntoRawFd::into_raw_fd)
278 .map(|raw_fd| unsafe { std::net::TcpStream::from_raw_fd(raw_fd) })
279 }
280
281 #[cfg(windows)]
282 {
283 use std::os::windows::io::{FromRawSocket, IntoRawSocket};
284 self.io
285 .into_inner()
286 .map(|io| io.into_raw_socket())
287 .map(|raw_socket| unsafe { std::net::TcpStream::from_raw_socket(raw_socket) })
288 }
289
290 #[cfg(target_os = "wasi")]
291 {
292 use std::os::fd::{FromRawFd, IntoRawFd};
293 self.io
294 .into_inner()
295 .map(|io| io.into_raw_fd())
296 .map(|raw_fd| unsafe { std::net::TcpStream::from_raw_fd(raw_fd) })
297 }
298 }
299
300 /// Returns the local address that this stream is bound to.
301 ///
302 /// # Examples
303 ///
304 /// ```no_run
305 /// use tokio::net::TcpStream;
306 ///
307 /// # async fn dox() -> Result<(), Box<dyn std::error::Error>> {
308 /// let stream = TcpStream::connect("127.0.0.1:8080").await?;
309 ///
310 /// println!("{:?}", stream.local_addr()?);
311 /// # Ok(())
312 /// # }
313 /// ```
314 pub fn local_addr(&self) -> io::Result<SocketAddr> {
315 self.io.local_addr()
316 }
317
318 /// Returns the value of the `SO_ERROR` option.
319 pub fn take_error(&self) -> io::Result<Option<io::Error>> {
320 self.io.take_error()
321 }
322
323 /// Returns the remote address that this stream is connected to.
324 ///
325 /// # Examples
326 ///
327 /// ```no_run
328 /// use tokio::net::TcpStream;
329 ///
330 /// # async fn dox() -> Result<(), Box<dyn std::error::Error>> {
331 /// let stream = TcpStream::connect("127.0.0.1:8080").await?;
332 ///
333 /// println!("{:?}", stream.peer_addr()?);
334 /// # Ok(())
335 /// # }
336 /// ```
337 pub fn peer_addr(&self) -> io::Result<SocketAddr> {
338 self.io.peer_addr()
339 }
340
341 /// Attempts to receive data on the socket, without removing that data from
342 /// the queue, registering the current task for wakeup if data is not yet
343 /// available.
344 ///
345 /// Note that on multiple calls to `poll_peek`, `poll_read` or
346 /// `poll_read_ready`, only the `Waker` from the `Context` passed to the
347 /// most recent call is scheduled to receive a wakeup. (However,
348 /// `poll_write` retains a second, independent waker.)
349 ///
350 /// # Return value
351 ///
352 /// The function returns:
353 ///
354 /// * `Poll::Pending` if data is not yet available.
355 /// * `Poll::Ready(Ok(n))` if data is available. `n` is the number of bytes peeked.
356 /// * `Poll::Ready(Err(e))` if an error is encountered.
357 ///
358 /// # Errors
359 ///
360 /// This function may encounter any standard I/O error except `WouldBlock`.
361 ///
362 /// # Examples
363 ///
364 /// ```no_run
365 /// use tokio::io::{self, ReadBuf};
366 /// use tokio::net::TcpStream;
367 ///
368 /// use std::future::poll_fn;
369 ///
370 /// #[tokio::main]
371 /// async fn main() -> io::Result<()> {
372 /// let stream = TcpStream::connect("127.0.0.1:8000").await?;
373 /// let mut buf = [0; 10];
374 /// let mut buf = ReadBuf::new(&mut buf);
375 ///
376 /// poll_fn(|cx| {
377 /// stream.poll_peek(cx, &mut buf)
378 /// }).await?;
379 ///
380 /// Ok(())
381 /// }
382 /// ```
383 pub fn poll_peek(
384 &self,
385 cx: &mut Context<'_>,
386 buf: &mut ReadBuf<'_>,
387 ) -> Poll<io::Result<usize>> {
388 loop {
389 let ev = ready!(self.io.registration().poll_read_ready(cx))?;
390
391 let b = unsafe {
392 &mut *(buf.unfilled_mut() as *mut [std::mem::MaybeUninit<u8>] as *mut [u8])
393 };
394
395 match self.io.peek(b) {
396 Ok(ret) => {
397 unsafe { buf.assume_init(ret) };
398 buf.advance(ret);
399 return Poll::Ready(Ok(ret));
400 }
401 Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
402 self.io.registration().clear_readiness(ev);
403 }
404 Err(e) => return Poll::Ready(Err(e)),
405 }
406 }
407 }
408
409 /// Waits for any of the requested ready states.
410 ///
411 /// This function is usually paired with `try_read()` or `try_write()`. It
412 /// can be used to concurrently read / write to the same socket on a single
413 /// task without splitting the socket.
414 ///
415 /// The function may complete without the socket being ready. This is a
416 /// false-positive and attempting an operation will return with
417 /// `io::ErrorKind::WouldBlock`. The function can also return with an empty
418 /// [`Ready`] set, so you should always check the returned value and possibly
419 /// wait again if the requested states are not set.
420 ///
421 /// # Cancel safety
422 ///
423 /// This method is cancel safe. Once a readiness event occurs, the method
424 /// will continue to return immediately until the readiness event is
425 /// consumed by an attempt to read or write that fails with `WouldBlock` or
426 /// `Poll::Pending`.
427 ///
428 /// # Examples
429 ///
430 /// Concurrently read and write to the stream on the same task without
431 /// splitting.
432 ///
433 /// ```no_run
434 /// use tokio::io::Interest;
435 /// use tokio::net::TcpStream;
436 /// use std::error::Error;
437 /// use std::io;
438 ///
439 /// #[tokio::main]
440 /// async fn main() -> Result<(), Box<dyn Error>> {
441 /// let stream = TcpStream::connect("127.0.0.1:8080").await?;
442 ///
443 /// loop {
444 /// let ready = stream.ready(Interest::READABLE | Interest::WRITABLE).await?;
445 ///
446 /// if ready.is_readable() {
447 /// let mut data = vec![0; 1024];
448 /// // Try to read data, this may still fail with `WouldBlock`
449 /// // if the readiness event is a false positive.
450 /// match stream.try_read(&mut data) {
451 /// Ok(n) => {
452 /// println!("read {} bytes", n);
453 /// }
454 /// Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
455 /// continue;
456 /// }
457 /// Err(e) => {
458 /// return Err(e.into());
459 /// }
460 /// }
461 ///
462 /// }
463 ///
464 /// if ready.is_writable() {
465 /// // Try to write data, this may still fail with `WouldBlock`
466 /// // if the readiness event is a false positive.
467 /// match stream.try_write(b"hello world") {
468 /// Ok(n) => {
469 /// println!("write {} bytes", n);
470 /// }
471 /// Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
472 /// continue
473 /// }
474 /// Err(e) => {
475 /// return Err(e.into());
476 /// }
477 /// }
478 /// }
479 /// }
480 /// }
481 /// ```
482 pub async fn ready(&self, interest: Interest) -> io::Result<Ready> {
483 let event = self.io.registration().readiness(interest).await?;
484 Ok(event.ready)
485 }
486
487 /// Waits for the socket to become readable.
488 ///
489 /// This function is equivalent to `ready(Interest::READABLE)` and is usually
490 /// paired with `try_read()`.
491 ///
492 /// # Cancel safety
493 ///
494 /// This method is cancel safe. Once a readiness event occurs, the method
495 /// will continue to return immediately until the readiness event is
496 /// consumed by an attempt to read that fails with `WouldBlock` or
497 /// `Poll::Pending`.
498 ///
499 /// # Examples
500 ///
501 /// ```no_run
502 /// use tokio::net::TcpStream;
503 /// use std::error::Error;
504 /// use std::io;
505 ///
506 /// #[tokio::main]
507 /// async fn main() -> Result<(), Box<dyn Error>> {
508 /// // Connect to a peer
509 /// let stream = TcpStream::connect("127.0.0.1:8080").await?;
510 ///
511 /// let mut msg = vec![0; 1024];
512 ///
513 /// loop {
514 /// // Wait for the socket to be readable
515 /// stream.readable().await?;
516 ///
517 /// // Try to read data, this may still fail with `WouldBlock`
518 /// // if the readiness event is a false positive.
519 /// match stream.try_read(&mut msg) {
520 /// Ok(n) => {
521 /// msg.truncate(n);
522 /// break;
523 /// }
524 /// Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
525 /// continue;
526 /// }
527 /// Err(e) => {
528 /// return Err(e.into());
529 /// }
530 /// }
531 /// }
532 ///
533 /// println!("GOT = {:?}", msg);
534 /// Ok(())
535 /// }
536 /// ```
537 pub async fn readable(&self) -> io::Result<()> {
538 self.ready(Interest::READABLE).await?;
539 Ok(())
540 }
541
542 /// Polls for read readiness.
543 ///
544 /// If the tcp stream is not currently ready for reading, this method will
545 /// store a clone of the `Waker` from the provided `Context`. When the tcp
546 /// stream becomes ready for reading, `Waker::wake` will be called on the
547 /// waker.
548 ///
549 /// Note that on multiple calls to `poll_read_ready`, `poll_read` or
550 /// `poll_peek`, only the `Waker` from the `Context` passed to the most
551 /// recent call is scheduled to receive a wakeup. (However,
552 /// `poll_write_ready` retains a second, independent waker.)
553 ///
554 /// This function is intended for cases where creating and pinning a future
555 /// via [`readable`] is not feasible. Where possible, using [`readable`] is
556 /// preferred, as this supports polling from multiple tasks at once.
557 ///
558 /// # Return value
559 ///
560 /// The function returns:
561 ///
562 /// * `Poll::Pending` if the tcp stream is not ready for reading.
563 /// * `Poll::Ready(Ok(()))` if the tcp stream is ready for reading.
564 /// * `Poll::Ready(Err(e))` if an error is encountered.
565 ///
566 /// # Errors
567 ///
568 /// This function may encounter any standard I/O error except `WouldBlock`.
569 ///
570 /// [`readable`]: method@Self::readable
571 pub fn poll_read_ready(&self, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
572 self.io.registration().poll_read_ready(cx).map_ok(|_| ())
573 }
574
575 /// Tries to read data from the stream into the provided buffer, returning how
576 /// many bytes were read.
577 ///
578 /// Receives any pending data from the socket but does not wait for new data
579 /// to arrive. On success, returns the number of bytes read. Because
580 /// `try_read()` is non-blocking, the buffer does not have to be stored by
581 /// the async task and can exist entirely on the stack.
582 ///
583 /// Usually, [`readable()`] or [`ready()`] is used with this function.
584 ///
585 /// [`readable()`]: TcpStream::readable()
586 /// [`ready()`]: TcpStream::ready()
587 ///
588 /// # Return
589 ///
590 /// If data is successfully read, `Ok(n)` is returned, where `n` is the
591 /// number of bytes read. If `n` is `0`, then it can indicate one of two scenarios:
592 ///
593 /// 1. The stream's read half is closed and will no longer yield data.
594 /// 2. The specified buffer was 0 bytes in length.
595 ///
596 /// If the stream is not ready to read data,
597 /// `Err(io::ErrorKind::WouldBlock)` is returned.
598 ///
599 /// # Examples
600 ///
601 /// ```no_run
602 /// use tokio::net::TcpStream;
603 /// use std::error::Error;
604 /// use std::io;
605 ///
606 /// #[tokio::main]
607 /// async fn main() -> Result<(), Box<dyn Error>> {
608 /// // Connect to a peer
609 /// let stream = TcpStream::connect("127.0.0.1:8080").await?;
610 ///
611 /// loop {
612 /// // Wait for the socket to be readable
613 /// stream.readable().await?;
614 ///
615 /// // Creating the buffer **after** the `await` prevents it from
616 /// // being stored in the async task.
617 /// let mut buf = [0; 4096];
618 ///
619 /// // Try to read data, this may still fail with `WouldBlock`
620 /// // if the readiness event is a false positive.
621 /// match stream.try_read(&mut buf) {
622 /// Ok(0) => break,
623 /// Ok(n) => {
624 /// println!("read {} bytes", n);
625 /// }
626 /// Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
627 /// continue;
628 /// }
629 /// Err(e) => {
630 /// return Err(e.into());
631 /// }
632 /// }
633 /// }
634 ///
635 /// Ok(())
636 /// }
637 /// ```
638 pub fn try_read(&self, buf: &mut [u8]) -> io::Result<usize> {
639 use std::io::Read;
640
641 self.io
642 .registration()
643 .try_io(Interest::READABLE, || (&*self.io).read(buf))
644 }
645
646 /// Tries to read data from the stream into the provided buffers, returning
647 /// how many bytes were read.
648 ///
649 /// Data is copied to fill each buffer in order, with the final buffer
650 /// written to possibly being only partially filled. This method behaves
651 /// equivalently to a single call to [`try_read()`] with concatenated
652 /// buffers.
653 ///
654 /// Receives any pending data from the socket but does not wait for new data
655 /// to arrive. On success, returns the number of bytes read. Because
656 /// `try_read_vectored()` is non-blocking, the buffer does not have to be
657 /// stored by the async task and can exist entirely on the stack.
658 ///
659 /// Usually, [`readable()`] or [`ready()`] is used with this function.
660 ///
661 /// [`try_read()`]: TcpStream::try_read()
662 /// [`readable()`]: TcpStream::readable()
663 /// [`ready()`]: TcpStream::ready()
664 ///
665 /// # Return
666 ///
667 /// If data is successfully read, `Ok(n)` is returned, where `n` is the
668 /// number of bytes read. `Ok(0)` indicates the stream's read half is closed
669 /// and will no longer yield data. If the stream is not ready to read data
670 /// `Err(io::ErrorKind::WouldBlock)` is returned.
671 ///
672 /// # Examples
673 ///
674 /// ```no_run
675 /// use tokio::net::TcpStream;
676 /// use std::error::Error;
677 /// use std::io::{self, IoSliceMut};
678 ///
679 /// #[tokio::main]
680 /// async fn main() -> Result<(), Box<dyn Error>> {
681 /// // Connect to a peer
682 /// let stream = TcpStream::connect("127.0.0.1:8080").await?;
683 ///
684 /// loop {
685 /// // Wait for the socket to be readable
686 /// stream.readable().await?;
687 ///
688 /// // Creating the buffer **after** the `await` prevents it from
689 /// // being stored in the async task.
690 /// let mut buf_a = [0; 512];
691 /// let mut buf_b = [0; 1024];
692 /// let mut bufs = [
693 /// IoSliceMut::new(&mut buf_a),
694 /// IoSliceMut::new(&mut buf_b),
695 /// ];
696 ///
697 /// // Try to read data, this may still fail with `WouldBlock`
698 /// // if the readiness event is a false positive.
699 /// match stream.try_read_vectored(&mut bufs) {
700 /// Ok(0) => break,
701 /// Ok(n) => {
702 /// println!("read {} bytes", n);
703 /// }
704 /// Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
705 /// continue;
706 /// }
707 /// Err(e) => {
708 /// return Err(e.into());
709 /// }
710 /// }
711 /// }
712 ///
713 /// Ok(())
714 /// }
715 /// ```
716 pub fn try_read_vectored(&self, bufs: &mut [io::IoSliceMut<'_>]) -> io::Result<usize> {
717 use std::io::Read;
718
719 self.io
720 .registration()
721 .try_io(Interest::READABLE, || (&*self.io).read_vectored(bufs))
722 }
723
724 cfg_io_util! {
725 /// Tries to read data from the stream into the provided buffer, advancing the
726 /// buffer's internal cursor, returning how many bytes were read.
727 ///
728 /// Receives any pending data from the socket but does not wait for new data
729 /// to arrive. On success, returns the number of bytes read. Because
730 /// `try_read_buf()` is non-blocking, the buffer does not have to be stored by
731 /// the async task and can exist entirely on the stack.
732 ///
733 /// Usually, [`readable()`] or [`ready()`] is used with this function.
734 ///
735 /// [`readable()`]: TcpStream::readable()
736 /// [`ready()`]: TcpStream::ready()
737 ///
738 /// # Return
739 ///
740 /// If data is successfully read, `Ok(n)` is returned, where `n` is the
741 /// number of bytes read. `Ok(0)` indicates the stream's read half is closed
742 /// and will no longer yield data. If the stream is not ready to read data
743 /// `Err(io::ErrorKind::WouldBlock)` is returned.
744 ///
745 /// # Examples
746 ///
747 /// ```no_run
748 /// use tokio::net::TcpStream;
749 /// use std::error::Error;
750 /// use std::io;
751 ///
752 /// #[tokio::main]
753 /// async fn main() -> Result<(), Box<dyn Error>> {
754 /// // Connect to a peer
755 /// let stream = TcpStream::connect("127.0.0.1:8080").await?;
756 ///
757 /// loop {
758 /// // Wait for the socket to be readable
759 /// stream.readable().await?;
760 ///
761 /// let mut buf = Vec::with_capacity(4096);
762 ///
763 /// // Try to read data, this may still fail with `WouldBlock`
764 /// // if the readiness event is a false positive.
765 /// match stream.try_read_buf(&mut buf) {
766 /// Ok(0) => break,
767 /// Ok(n) => {
768 /// println!("read {} bytes", n);
769 /// }
770 /// Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
771 /// continue;
772 /// }
773 /// Err(e) => {
774 /// return Err(e.into());
775 /// }
776 /// }
777 /// }
778 ///
779 /// Ok(())
780 /// }
781 /// ```
782 pub fn try_read_buf<B: BufMut>(&self, buf: &mut B) -> io::Result<usize> {
783 self.io.registration().try_io(Interest::READABLE, || {
784 use std::io::Read;
785
786 let dst = buf.chunk_mut();
787 let dst =
788 unsafe { &mut *(dst as *mut _ as *mut [std::mem::MaybeUninit<u8>] as *mut [u8]) };
789
790 // Safety: We trust `TcpStream::read` to have filled up `n` bytes in the
791 // buffer.
792 let n = (&*self.io).read(dst)?;
793
794 unsafe {
795 buf.advance_mut(n);
796 }
797
798 Ok(n)
799 })
800 }
801 }
802
803 /// Waits for the socket to become writable.
804 ///
805 /// This function is equivalent to `ready(Interest::WRITABLE)` and is usually
806 /// paired with `try_write()`.
807 ///
808 /// # Cancel safety
809 ///
810 /// This method is cancel safe. Once a readiness event occurs, the method
811 /// will continue to return immediately until the readiness event is
812 /// consumed by an attempt to write that fails with `WouldBlock` or
813 /// `Poll::Pending`.
814 ///
815 /// # Examples
816 ///
817 /// ```no_run
818 /// use tokio::net::TcpStream;
819 /// use std::error::Error;
820 /// use std::io;
821 ///
822 /// #[tokio::main]
823 /// async fn main() -> Result<(), Box<dyn Error>> {
824 /// // Connect to a peer
825 /// let stream = TcpStream::connect("127.0.0.1:8080").await?;
826 ///
827 /// loop {
828 /// // Wait for the socket to be writable
829 /// stream.writable().await?;
830 ///
831 /// // Try to write data, this may still fail with `WouldBlock`
832 /// // if the readiness event is a false positive.
833 /// match stream.try_write(b"hello world") {
834 /// Ok(n) => {
835 /// break;
836 /// }
837 /// Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
838 /// continue;
839 /// }
840 /// Err(e) => {
841 /// return Err(e.into());
842 /// }
843 /// }
844 /// }
845 ///
846 /// Ok(())
847 /// }
848 /// ```
849 pub async fn writable(&self) -> io::Result<()> {
850 self.ready(Interest::WRITABLE).await?;
851 Ok(())
852 }
853
854 /// Polls for write readiness.
855 ///
856 /// If the tcp stream is not currently ready for writing, this method will
857 /// store a clone of the `Waker` from the provided `Context`. When the tcp
858 /// stream becomes ready for writing, `Waker::wake` will be called on the
859 /// waker.
860 ///
861 /// Note that on multiple calls to `poll_write_ready` or `poll_write`, only
862 /// the `Waker` from the `Context` passed to the most recent call is
863 /// scheduled to receive a wakeup. (However, `poll_read_ready` retains a
864 /// second, independent waker.)
865 ///
866 /// This function is intended for cases where creating and pinning a future
867 /// via [`writable`] is not feasible. Where possible, using [`writable`] is
868 /// preferred, as this supports polling from multiple tasks at once.
869 ///
870 /// # Return value
871 ///
872 /// The function returns:
873 ///
874 /// * `Poll::Pending` if the tcp stream is not ready for writing.
875 /// * `Poll::Ready(Ok(()))` if the tcp stream is ready for writing.
876 /// * `Poll::Ready(Err(e))` if an error is encountered.
877 ///
878 /// # Errors
879 ///
880 /// This function may encounter any standard I/O error except `WouldBlock`.
881 ///
882 /// [`writable`]: method@Self::writable
883 pub fn poll_write_ready(&self, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
884 self.io.registration().poll_write_ready(cx).map_ok(|_| ())
885 }
886
887 /// Try to write a buffer to the stream, returning how many bytes were
888 /// written.
889 ///
890 /// The function will attempt to write the entire contents of `buf`, but
891 /// only part of the buffer may be written.
892 ///
893 /// This function is usually paired with `writable()`.
894 ///
895 /// # Return
896 ///
897 /// If data is successfully written, `Ok(n)` is returned, where `n` is the
898 /// number of bytes written. If the stream is not ready to write data,
899 /// `Err(io::ErrorKind::WouldBlock)` is returned.
900 ///
901 /// # Examples
902 ///
903 /// ```no_run
904 /// use tokio::net::TcpStream;
905 /// use std::error::Error;
906 /// use std::io;
907 ///
908 /// #[tokio::main]
909 /// async fn main() -> Result<(), Box<dyn Error>> {
910 /// // Connect to a peer
911 /// let stream = TcpStream::connect("127.0.0.1:8080").await?;
912 ///
913 /// loop {
914 /// // Wait for the socket to be writable
915 /// stream.writable().await?;
916 ///
917 /// // Try to write data, this may still fail with `WouldBlock`
918 /// // if the readiness event is a false positive.
919 /// match stream.try_write(b"hello world") {
920 /// Ok(n) => {
921 /// break;
922 /// }
923 /// Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
924 /// continue;
925 /// }
926 /// Err(e) => {
927 /// return Err(e.into());
928 /// }
929 /// }
930 /// }
931 ///
932 /// Ok(())
933 /// }
934 /// ```
935 pub fn try_write(&self, buf: &[u8]) -> io::Result<usize> {
936 use std::io::Write;
937
938 self.io
939 .registration()
940 .try_io(Interest::WRITABLE, || (&*self.io).write(buf))
941 }
942
943 /// Tries to write several buffers to the stream, returning how many bytes
944 /// were written.
945 ///
946 /// Data is written from each buffer in order, with the final buffer read
947 /// from possibly being only partially consumed. This method behaves
948 /// equivalently to a single call to [`try_write()`] with concatenated
949 /// buffers.
950 ///
951 /// This function is usually paired with `writable()`.
952 ///
953 /// [`try_write()`]: TcpStream::try_write()
954 ///
955 /// # Return
956 ///
957 /// If data is successfully written, `Ok(n)` is returned, where `n` is the
958 /// number of bytes written. If the stream is not ready to write data,
959 /// `Err(io::ErrorKind::WouldBlock)` is returned.
960 ///
961 /// # Examples
962 ///
963 /// ```no_run
964 /// use tokio::net::TcpStream;
965 /// use std::error::Error;
966 /// use std::io;
967 ///
968 /// #[tokio::main]
969 /// async fn main() -> Result<(), Box<dyn Error>> {
970 /// // Connect to a peer
971 /// let stream = TcpStream::connect("127.0.0.1:8080").await?;
972 ///
973 /// let bufs = [io::IoSlice::new(b"hello "), io::IoSlice::new(b"world")];
974 ///
975 /// loop {
976 /// // Wait for the socket to be writable
977 /// stream.writable().await?;
978 ///
979 /// // Try to write data, this may still fail with `WouldBlock`
980 /// // if the readiness event is a false positive.
981 /// match stream.try_write_vectored(&bufs) {
982 /// Ok(n) => {
983 /// break;
984 /// }
985 /// Err(ref e) if e.kind() == io::ErrorKind::WouldBlock => {
986 /// continue;
987 /// }
988 /// Err(e) => {
989 /// return Err(e.into());
990 /// }
991 /// }
992 /// }
993 ///
994 /// Ok(())
995 /// }
996 /// ```
997 pub fn try_write_vectored(&self, bufs: &[io::IoSlice<'_>]) -> io::Result<usize> {
998 use std::io::Write;
999
1000 self.io
1001 .registration()
1002 .try_io(Interest::WRITABLE, || (&*self.io).write_vectored(bufs))
1003 }
1004
1005 /// Tries to read or write from the socket using a user-provided IO operation.
1006 ///
1007 /// If the socket is ready, the provided closure is called. The closure
1008 /// should attempt to perform IO operation on the socket by manually
1009 /// calling the appropriate syscall. If the operation fails because the
1010 /// socket is not actually ready, then the closure should return a
1011 /// `WouldBlock` error and the readiness flag is cleared. The return value
1012 /// of the closure is then returned by `try_io`.
1013 ///
1014 /// If the socket is not ready, then the closure is not called
1015 /// and a `WouldBlock` error is returned.
1016 ///
1017 /// The closure should only return a `WouldBlock` error if it has performed
1018 /// an IO operation on the socket that failed due to the socket not being
1019 /// ready. Returning a `WouldBlock` error in any other situation will
1020 /// incorrectly clear the readiness flag, which can cause the socket to
1021 /// behave incorrectly.
1022 ///
1023 /// The closure should not perform the IO operation using any of the methods
1024 /// defined on the Tokio `TcpStream` type, as this will mess with the
1025 /// readiness flag and can cause the socket to behave incorrectly.
1026 ///
1027 /// This method is not intended to be used with combined interests.
1028 /// The closure should perform only one type of IO operation, so it should not
1029 /// require more than one ready state. This method may panic or sleep forever
1030 /// if it is called with a combined interest.
1031 ///
1032 /// Usually, [`readable()`], [`writable()`] or [`ready()`] is used with this function.
1033 ///
1034 /// [`readable()`]: TcpStream::readable()
1035 /// [`writable()`]: TcpStream::writable()
1036 /// [`ready()`]: TcpStream::ready()
1037 pub fn try_io<R>(
1038 &self,
1039 interest: Interest,
1040 f: impl FnOnce() -> io::Result<R>,
1041 ) -> io::Result<R> {
1042 self.io
1043 .registration()
1044 .try_io(interest, || self.io.try_io(f))
1045 }
1046
1047 /// Reads or writes from the socket using a user-provided IO operation.
1048 ///
1049 /// The readiness of the socket is awaited and when the socket is ready,
1050 /// the provided closure is called. The closure should attempt to perform
1051 /// IO operation on the socket by manually calling the appropriate syscall.
1052 /// If the operation fails because the socket is not actually ready,
1053 /// then the closure should return a `WouldBlock` error. In such case the
1054 /// readiness flag is cleared and the socket readiness is awaited again.
1055 /// This loop is repeated until the closure returns an `Ok` or an error
1056 /// other than `WouldBlock`.
1057 ///
1058 /// The closure should only return a `WouldBlock` error if it has performed
1059 /// an IO operation on the socket that failed due to the socket not being
1060 /// ready. Returning a `WouldBlock` error in any other situation will
1061 /// incorrectly clear the readiness flag, which can cause the socket to
1062 /// behave incorrectly.
1063 ///
1064 /// The closure should not perform the IO operation using any of the methods
1065 /// defined on the Tokio `TcpStream` type, as this will mess with the
1066 /// readiness flag and can cause the socket to behave incorrectly.
1067 ///
1068 /// This method is not intended to be used with combined interests.
1069 /// The closure should perform only one type of IO operation, so it should not
1070 /// require more than one ready state. This method may panic or sleep forever
1071 /// if it is called with a combined interest.
1072 pub async fn async_io<R>(
1073 &self,
1074 interest: Interest,
1075 mut f: impl FnMut() -> io::Result<R>,
1076 ) -> io::Result<R> {
1077 self.io
1078 .registration()
1079 .async_io(interest, || self.io.try_io(&mut f))
1080 .await
1081 }
1082
1083 /// Receives data on the socket from the remote address to which it is
1084 /// connected, without removing that data from the queue. On success,
1085 /// returns the number of bytes peeked.
1086 ///
1087 /// Successive calls return the same data. This is accomplished by passing
1088 /// `MSG_PEEK` as a flag to the underlying `recv` system call.
1089 ///
1090 /// # Cancel safety
1091 ///
1092 /// This method is cancel safe. If the method is used as a branch in
1093 /// [`tokio::select!`](crate::select) and another branch
1094 /// completes first, then it is guaranteed that no peek was performed, and
1095 /// that `buf` has not been modified.
1096 ///
1097 /// # Examples
1098 ///
1099 /// ```no_run
1100 /// use tokio::net::TcpStream;
1101 /// use tokio::io::AsyncReadExt;
1102 /// use std::error::Error;
1103 ///
1104 /// #[tokio::main]
1105 /// async fn main() -> Result<(), Box<dyn Error>> {
1106 /// // Connect to a peer
1107 /// let mut stream = TcpStream::connect("127.0.0.1:8080").await?;
1108 ///
1109 /// let mut b1 = [0; 10];
1110 /// let mut b2 = [0; 10];
1111 ///
1112 /// // Peek at the data
1113 /// let n = stream.peek(&mut b1).await?;
1114 ///
1115 /// // Read the data
1116 /// assert_eq!(n, stream.read(&mut b2[..n]).await?);
1117 /// assert_eq!(&b1[..n], &b2[..n]);
1118 ///
1119 /// Ok(())
1120 /// }
1121 /// ```
1122 ///
1123 /// The [`read`] method is defined on the [`AsyncReadExt`] trait.
1124 ///
1125 /// [`read`]: fn@crate::io::AsyncReadExt::read
1126 /// [`AsyncReadExt`]: trait@crate::io::AsyncReadExt
1127 pub async fn peek(&self, buf: &mut [u8]) -> io::Result<usize> {
1128 self.io
1129 .registration()
1130 .async_io(Interest::READABLE, || self.io.peek(buf))
1131 .await
1132 }
1133
1134 /// Shuts down the read, write, or both halves of this connection.
1135 ///
1136 /// This function will cause all pending and future I/O on the specified
1137 /// portions to return immediately with an appropriate value (see the
1138 /// documentation of `Shutdown`).
1139 ///
1140 /// Remark: this function transforms `Err(std::io::ErrorKind::NotConnected)` to `Ok(())`.
1141 /// It does this to abstract away OS specific logic and to prevent a race condition between
1142 /// this function call and the OS closing this socket because of external events (e.g. TCP reset).
1143 /// See <https://github.com/tokio-rs/tokio/issues/4665> for more information.
1144 pub(super) fn shutdown_std(&self, how: Shutdown) -> io::Result<()> {
1145 match self.io.shutdown(how) {
1146 Err(err) if err.kind() == std::io::ErrorKind::NotConnected => Ok(()),
1147 result => result,
1148 }
1149 }
1150
1151 /// Gets the value of the `TCP_NODELAY` option on this socket.
1152 ///
1153 /// For more information about this option, see [`set_nodelay`].
1154 ///
1155 /// [`set_nodelay`]: TcpStream::set_nodelay
1156 ///
1157 /// # Examples
1158 ///
1159 /// ```no_run
1160 /// use tokio::net::TcpStream;
1161 ///
1162 /// # async fn dox() -> Result<(), Box<dyn std::error::Error>> {
1163 /// let stream = TcpStream::connect("127.0.0.1:8080").await?;
1164 ///
1165 /// println!("{:?}", stream.nodelay()?);
1166 /// # Ok(())
1167 /// # }
1168 /// ```
1169 pub fn nodelay(&self) -> io::Result<bool> {
1170 self.io.nodelay()
1171 }
1172
1173 /// Sets the value of the `TCP_NODELAY` option on this socket.
1174 ///
1175 /// If set, this option disables the Nagle algorithm. This means that
1176 /// segments are always sent as soon as possible, even if there is only a
1177 /// small amount of data. When not set, data is buffered until there is a
1178 /// sufficient amount to send out, thereby avoiding the frequent sending of
1179 /// small packets.
1180 ///
1181 /// # Examples
1182 ///
1183 /// ```no_run
1184 /// use tokio::net::TcpStream;
1185 ///
1186 /// # async fn dox() -> Result<(), Box<dyn std::error::Error>> {
1187 /// let stream = TcpStream::connect("127.0.0.1:8080").await?;
1188 ///
1189 /// stream.set_nodelay(true)?;
1190 /// # Ok(())
1191 /// # }
1192 /// ```
1193 pub fn set_nodelay(&self, nodelay: bool) -> io::Result<()> {
1194 self.io.set_nodelay(nodelay)
1195 }
1196
1197 /// Gets the value of the `TCP_QUICKACK` option on this socket.
1198 ///
1199 /// For more information about this option, see [`TcpStream::set_quickack`].
1200 ///
1201 /// # Examples
1202 ///
1203 /// ```no_run
1204 /// use tokio::net::TcpStream;
1205 ///
1206 /// # async fn dox() -> Result<(), Box<dyn std::error::Error>> {
1207 /// let stream = TcpStream::connect("127.0.0.1:8080").await?;
1208 ///
1209 /// stream.quickack()?;
1210 /// # Ok(())
1211 /// # }
1212 /// ```
1213 #[cfg(any(
1214 target_os = "linux",
1215 target_os = "android",
1216 target_os = "fuchsia",
1217 target_os = "cygwin",
1218 ))]
1219 #[cfg_attr(
1220 docsrs,
1221 doc(cfg(any(
1222 target_os = "linux",
1223 target_os = "android",
1224 target_os = "fuchsia",
1225 target_os = "cygwin"
1226 )))
1227 )]
1228 pub fn quickack(&self) -> io::Result<bool> {
1229 socket2::SockRef::from(self).tcp_quickack()
1230 }
1231
1232 /// Enable or disable `TCP_QUICKACK`.
1233 ///
1234 /// This flag causes Linux to eagerly send `ACK`s rather than delaying them.
1235 /// Linux may reset this flag after further operations on the socket.
1236 ///
1237 /// See [`man 7 tcp`](https://man7.org/linux/man-pages/man7/tcp.7.html) and
1238 /// [TCP delayed acknowledgment](https://en.wikipedia.org/wiki/TCP_delayed_acknowledgment)
1239 /// for more information.
1240 ///
1241 /// # Examples
1242 ///
1243 /// ```no_run
1244 /// use tokio::net::TcpStream;
1245 ///
1246 /// # async fn dox() -> Result<(), Box<dyn std::error::Error>> {
1247 /// let stream = TcpStream::connect("127.0.0.1:8080").await?;
1248 ///
1249 /// stream.set_quickack(true)?;
1250 /// # Ok(())
1251 /// # }
1252 /// ```
1253 #[cfg(any(
1254 target_os = "linux",
1255 target_os = "android",
1256 target_os = "fuchsia",
1257 target_os = "cygwin",
1258 ))]
1259 #[cfg_attr(
1260 docsrs,
1261 doc(cfg(any(
1262 target_os = "linux",
1263 target_os = "android",
1264 target_os = "fuchsia",
1265 target_os = "cygwin"
1266 )))
1267 )]
1268 pub fn set_quickack(&self, quickack: bool) -> io::Result<()> {
1269 socket2::SockRef::from(self).set_tcp_quickack(quickack)
1270 }
1271
1272 cfg_not_wasi! {
1273 /// Reads the linger duration for this socket by getting the `SO_LINGER`
1274 /// option.
1275 ///
1276 /// For more information about this option, see [`set_zero_linger`] and [`set_linger`].
1277 ///
1278 /// [`set_linger`]: TcpStream::set_linger
1279 /// [`set_zero_linger`]: TcpStream::set_zero_linger
1280 ///
1281 /// # Examples
1282 ///
1283 /// ```no_run
1284 /// use tokio::net::TcpStream;
1285 ///
1286 /// # async fn dox() -> Result<(), Box<dyn std::error::Error>> {
1287 /// let stream = TcpStream::connect("127.0.0.1:8080").await?;
1288 ///
1289 /// println!("{:?}", stream.linger()?);
1290 /// # Ok(())
1291 /// # }
1292 /// ```
1293 pub fn linger(&self) -> io::Result<Option<Duration>> {
1294 socket2::SockRef::from(self).linger()
1295 }
1296
1297 /// Sets the linger duration of this socket by setting the `SO_LINGER` option.
1298 ///
1299 /// This option controls the action taken when a stream has unsent messages and the stream is
1300 /// closed. If `SO_LINGER` is set, the system shall block the process until it can transmit the
1301 /// data or until the time expires.
1302 ///
1303 /// If `SO_LINGER` is not specified, and the stream is closed, the system handles the call in a
1304 /// way that allows the process to continue as quickly as possible.
1305 ///
1306 /// This option is deprecated because setting `SO_LINGER` on a socket used with Tokio is
1307 /// always incorrect as it leads to blocking the thread when the socket is closed. For more
1308 /// details, please see:
1309 ///
1310 /// > Volumes of communications have been devoted to the intricacies of `SO_LINGER` versus
1311 /// > non-blocking (`O_NONBLOCK`) sockets. From what I can tell, the final word is: don't
1312 /// > do it. Rely on the `shutdown()`-followed-by-`read()`-eof technique instead.
1313 /// >
1314 /// > From [The ultimate `SO_LINGER` page, or: why is my tcp not reliable](https://blog.netherlabs.nl/articles/2009/01/18/the-ultimate-so_linger-page-or-why-is-my-tcp-not-reliable)
1315 ///
1316 /// Although this method is deprecated, it will not be removed from Tokio.
1317 ///
1318 /// Note that the special case of setting `SO_LINGER` to zero does not lead to blocking.
1319 /// Tokio provides [`set_zero_linger`](Self::set_zero_linger) for this purpose.
1320 ///
1321 /// # Examples
1322 ///
1323 /// ```no_run
1324 /// # #![allow(deprecated)]
1325 /// use tokio::net::TcpStream;
1326 ///
1327 /// # async fn dox() -> Result<(), Box<dyn std::error::Error>> {
1328 /// let stream = TcpStream::connect("127.0.0.1:8080").await?;
1329 ///
1330 /// stream.set_linger(None)?;
1331 /// # Ok(())
1332 /// # }
1333 /// ```
1334 #[deprecated = "`SO_LINGER` causes the socket to block the thread on drop"]
1335 pub fn set_linger(&self, dur: Option<Duration>) -> io::Result<()> {
1336 socket2::SockRef::from(self).set_linger(dur)
1337 }
1338
1339 /// Sets a linger duration of zero on this socket by setting the `SO_LINGER` option.
1340 ///
1341 /// This causes the connection to be forcefully aborted ("abortive close") when the socket
1342 /// is dropped or closed. Instead of the normal TCP shutdown handshake (`FIN`/`ACK`), a TCP
1343 /// `RST` (reset) segment is sent to the peer, and the socket immediately discards any
1344 /// unsent data residing in the socket send buffer. This prevents the socket from entering
1345 /// the `TIME_WAIT` state after closing it.
1346 ///
1347 /// This is a destructive action. Any data currently buffered by the OS but not yet
1348 /// transmitted will be lost. The peer will likely receive a "Connection Reset" error
1349 /// rather than a clean end-of-stream.
1350 ///
1351 /// See the documentation for [`set_linger`](Self::set_linger) for additional details on
1352 /// how `SO_LINGER` works.
1353 ///
1354 /// # Examples
1355 ///
1356 /// ```no_run
1357 /// use std::time::Duration;
1358 /// use tokio::net::TcpStream;
1359 ///
1360 /// # async fn dox() -> Result<(), Box<dyn std::error::Error>> {
1361 /// let stream = TcpStream::connect("127.0.0.1:8080").await?;
1362 ///
1363 /// stream.set_zero_linger()?;
1364 /// assert_eq!(stream.linger()?, Some(Duration::ZERO));
1365 /// # Ok(())
1366 /// # }
1367 /// ```
1368 pub fn set_zero_linger(&self) -> io::Result<()> {
1369 socket2::SockRef::from(self).set_linger(Some(Duration::ZERO))
1370 }
1371 }
1372
1373 /// Gets the value of the `IP_TTL` option for this socket.
1374 ///
1375 /// For more information about this option, see [`set_ttl`].
1376 ///
1377 /// [`set_ttl`]: TcpStream::set_ttl
1378 ///
1379 /// # Examples
1380 ///
1381 /// ```no_run
1382 /// use tokio::net::TcpStream;
1383 ///
1384 /// # async fn dox() -> Result<(), Box<dyn std::error::Error>> {
1385 /// let stream = TcpStream::connect("127.0.0.1:8080").await?;
1386 ///
1387 /// println!("{:?}", stream.ttl()?);
1388 /// # Ok(())
1389 /// # }
1390 /// ```
1391 pub fn ttl(&self) -> io::Result<u32> {
1392 self.io.ttl()
1393 }
1394
1395 /// Sets the value for the `IP_TTL` option on this socket.
1396 ///
1397 /// This value sets the time-to-live field that is used in every packet sent
1398 /// from this socket.
1399 ///
1400 /// # Examples
1401 ///
1402 /// ```no_run
1403 /// use tokio::net::TcpStream;
1404 ///
1405 /// # async fn dox() -> Result<(), Box<dyn std::error::Error>> {
1406 /// let stream = TcpStream::connect("127.0.0.1:8080").await?;
1407 ///
1408 /// stream.set_ttl(123)?;
1409 /// # Ok(())
1410 /// # }
1411 /// ```
1412 pub fn set_ttl(&self, ttl: u32) -> io::Result<()> {
1413 self.io.set_ttl(ttl)
1414 }
1415
1416 // These lifetime markers also appear in the generated documentation, and make
1417 // it more clear that this is a *borrowed* split.
1418 #[allow(clippy::needless_lifetimes)]
1419 /// Splits a `TcpStream` into a read half and a write half, which can be used
1420 /// to read and write the stream concurrently.
1421 ///
1422 /// This method is more efficient than [`into_split`], but the halves cannot be
1423 /// moved into independently spawned tasks.
1424 ///
1425 /// [`into_split`]: TcpStream::into_split()
1426 pub fn split<'a>(&'a mut self) -> (ReadHalf<'a>, WriteHalf<'a>) {
1427 split(self)
1428 }
1429
1430 /// Splits a `TcpStream` into a read half and a write half, which can be used
1431 /// to read and write the stream concurrently.
1432 ///
1433 /// Unlike [`split`], the owned halves can be moved to separate tasks, however
1434 /// this comes at the cost of a heap allocation.
1435 ///
1436 /// **Note:** Dropping the write half will shut down the write half of the TCP
1437 /// stream. This is equivalent to calling [`shutdown()`] on the `TcpStream`.
1438 ///
1439 /// [`split`]: TcpStream::split()
1440 /// [`shutdown()`]: fn@crate::io::AsyncWriteExt::shutdown
1441 pub fn into_split(self) -> (OwnedReadHalf, OwnedWriteHalf) {
1442 split_owned(self)
1443 }
1444
1445 // == Poll IO functions that takes `&self` ==
1446 //
1447 // To read or write without mutable access to the `TcpStream`, combine the
1448 // `poll_read_ready` or `poll_write_ready` methods with the `try_read` or
1449 // `try_write` methods.
1450
1451 pub(crate) fn poll_read_priv(
1452 &self,
1453 cx: &mut Context<'_>,
1454 buf: &mut ReadBuf<'_>,
1455 ) -> Poll<io::Result<()>> {
1456 // Safety: `TcpStream::read` correctly handles reads into uninitialized memory
1457 unsafe { self.io.poll_read(cx, buf) }
1458 }
1459
1460 pub(super) fn poll_write_priv(
1461 &self,
1462 cx: &mut Context<'_>,
1463 buf: &[u8],
1464 ) -> Poll<io::Result<usize>> {
1465 self.io.poll_write(cx, buf)
1466 }
1467
1468 pub(super) fn poll_write_vectored_priv(
1469 &self,
1470 cx: &mut Context<'_>,
1471 bufs: &[io::IoSlice<'_>],
1472 ) -> Poll<io::Result<usize>> {
1473 self.io.poll_write_vectored(cx, bufs)
1474 }
1475}
1476
1477impl TryFrom<std::net::TcpStream> for TcpStream {
1478 type Error = io::Error;
1479
1480 /// Consumes stream, returning the tokio I/O object.
1481 ///
1482 /// This is equivalent to
1483 /// [`TcpStream::from_std(stream)`](TcpStream::from_std).
1484 fn try_from(stream: std::net::TcpStream) -> Result<Self, Self::Error> {
1485 Self::from_std(stream)
1486 }
1487}
1488
1489// ===== impl Read / Write =====
1490
1491impl AsyncRead for TcpStream {
1492 fn poll_read(
1493 self: Pin<&mut Self>,
1494 cx: &mut Context<'_>,
1495 buf: &mut ReadBuf<'_>,
1496 ) -> Poll<io::Result<()>> {
1497 self.poll_read_priv(cx, buf)
1498 }
1499}
1500
1501impl AsyncWrite for TcpStream {
1502 fn poll_write(
1503 self: Pin<&mut Self>,
1504 cx: &mut Context<'_>,
1505 buf: &[u8],
1506 ) -> Poll<io::Result<usize>> {
1507 self.poll_write_priv(cx, buf)
1508 }
1509
1510 fn poll_write_vectored(
1511 self: Pin<&mut Self>,
1512 cx: &mut Context<'_>,
1513 bufs: &[io::IoSlice<'_>],
1514 ) -> Poll<io::Result<usize>> {
1515 self.poll_write_vectored_priv(cx, bufs)
1516 }
1517
1518 fn is_write_vectored(&self) -> bool {
1519 true
1520 }
1521
1522 #[inline]
1523 fn poll_flush(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<io::Result<()>> {
1524 // tcp flush is a no-op
1525 Poll::Ready(Ok(()))
1526 }
1527
1528 fn poll_shutdown(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<io::Result<()>> {
1529 self.shutdown_std(std::net::Shutdown::Write)?;
1530 Poll::Ready(Ok(()))
1531 }
1532}
1533
1534impl fmt::Debug for TcpStream {
1535 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1536 // skip PollEvented noise
1537 (*self.io).fmt(f)
1538 }
1539}
1540
1541impl AsRef<Self> for TcpStream {
1542 fn as_ref(&self) -> &Self {
1543 self
1544 }
1545}
1546
1547#[cfg(unix)]
1548mod sys {
1549 use super::TcpStream;
1550 use std::os::unix::prelude::*;
1551
1552 impl AsRawFd for TcpStream {
1553 fn as_raw_fd(&self) -> RawFd {
1554 self.io.as_raw_fd()
1555 }
1556 }
1557
1558 impl AsFd for TcpStream {
1559 fn as_fd(&self) -> BorrowedFd<'_> {
1560 unsafe { BorrowedFd::borrow_raw(self.as_raw_fd()) }
1561 }
1562 }
1563}
1564
1565cfg_windows! {
1566 use crate::os::windows::io::{AsRawSocket, RawSocket, AsSocket, BorrowedSocket};
1567
1568 impl AsRawSocket for TcpStream {
1569 fn as_raw_socket(&self) -> RawSocket {
1570 self.io.as_raw_socket()
1571 }
1572 }
1573
1574 impl AsSocket for TcpStream {
1575 fn as_socket(&self) -> BorrowedSocket<'_> {
1576 unsafe { BorrowedSocket::borrow_raw(self.as_raw_socket()) }
1577 }
1578 }
1579}
1580
1581#[cfg(all(tokio_unstable, target_os = "wasi"))]
1582mod sys {
1583 use super::TcpStream;
1584 use std::os::fd::{AsFd, AsRawFd, BorrowedFd, RawFd};
1585
1586 impl AsRawFd for TcpStream {
1587 fn as_raw_fd(&self) -> RawFd {
1588 self.io.as_raw_fd()
1589 }
1590 }
1591
1592 impl AsFd for TcpStream {
1593 fn as_fd(&self) -> BorrowedFd<'_> {
1594 unsafe { BorrowedFd::borrow_raw(self.as_raw_fd()) }
1595 }
1596 }
1597}