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