跳到主要内容

TcpListener

搜索

结构体 TcpListener 

源代码
pub struct TcpListener { /* 私有字段 */ }
展开描述

监听连接的 TCP 套接字服务器。

你可以使用 accept 方法接受新连接。

TcpListener 可以通过 TcpListenerStream 转换为 Stream

当该值被 drop 时,套接字将被关闭。

§错误

请注意,接受连接可能会导致各种错误,并非所有错误都一定是致命的——例如打开的文件描述符过多,或者对端在等待接受队列时关闭连接。如果不以任何方式处理这些情况,它们将终止流。

§示例

使用 accept

use tokio::net::TcpListener;

use std::io;

async fn process_socket<T>(socket: T) {
    // do work with socket here
}

#[tokio::main]
async fn main() -> io::Result<()> {
    let listener = TcpListener::bind("127.0.0.1:8080").await?;

    loop {
        let (socket, _) = listener.accept().await?;
        process_socket(socket).await;
    }
}

实现§

源代码§

impl TcpListener

源代码

pub async fn bind<A: ToSocketAddrs>(addr: A) -> Result<TcpListener>

创建一个新的 TcpListener,它将绑定到指定的地址。

返回的监听器已准备好接受连接。

使用端口号 0 绑定将请求操作系统为此监听器分配一个端口。所分配的端口可以通过 local_addr 方法查询。

地址类型可以是 ToSocketAddrs trait 的任何实现者。如果 addr 产生多个地址,则会依次尝试与每个地址进行绑定,直到其中一个成功并返回监听器。如果没有任何地址成功创建监听器,则返回最后一次尝试(最后一个地址)的错误。

此函数在 Unix 上的套接字上设置 SO_REUSEADDR 选项。

要在绑定之前配置套接字,可以使用 TcpSocket 类型。

§示例
use tokio::net::TcpListener;
use std::io;

#[tokio::main]
async fn main() -> io::Result<()> {
    let listener = TcpListener::bind("127.0.0.1:2345").await?;

    // use the listener

    Ok(())
}
源代码

pub async fn accept(&self) -> Result<(TcpStream, SocketAddr)>

从此监听器接受一个新的传入连接。

一旦建立新的 TCP 连接,此函数就会让步。连接建立后,将返回相应的 TcpStream 和远程对等方的地址。

§取消安全性

此方法是可安全取消的。如果在 tokio::select! 语句中将此方法用作事件,并且其他某个分支先完成,则可以保证此方法未接受任何新连接。

§示例
use tokio::net::TcpListener;

use std::io;

#[tokio::main]
async fn main() -> io::Result<()> {
    let listener = TcpListener::bind("127.0.0.1:8080").await?;

    match listener.accept().await {
        Ok((_socket, addr)) => println!("new client: {:?}", addr),
        Err(e) => println!("couldn't get client: {:?}", e),
    }

    Ok(())
}
源代码

pub fn poll_accept( &self, cx: &mut Context<'_>, ) -> Poll<Result<(TcpStream, SocketAddr)>>

轮询以接受到此监听器的新传入连接。

如果没有连接可接受,则返回 Poll::Pending,并且当前任务将由 waker 通知。请注意,在多次调用 poll_accept 时,只有传递给最近一次调用的 Context 中的 Waker 会被调度接收唤醒。

源代码

pub fn from_std(listener: TcpListener) -> Result<TcpListener>

std::net::TcpListener 创建一个新的 TcpListener

此函数旨在用于将标准库的 TCP 监听器包装为 Tokio 等价物。

此 API 通常与 socket2 crate 和 Socket 类型配对使用,以便在将监听器交给底层事件循环之前构建并自定义它。这允许配置诸如 SO_REUSEPORT、绑定到多个地址等选项。

§注意

调用者负责确保监听器处于非阻塞模式。否则,对监听器的所有 I/O 操作都会阻塞线程,从而导致意外行为。可以使用 set_nonblocking 设置非阻塞模式。

在阻塞模式下传入监听器始终是错误的,这种情况下行为将来可能会发生变化。例如,可能会发生 panic。

§示例
use std::error::Error;
use tokio::net::TcpListener;

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    let std_listener = std::net::TcpListener::bind("127.0.0.1:0")?;
    std_listener.set_nonblocking(true)?;
    let listener = TcpListener::from_std(std_listener)?;
    Ok(())
}
§恐慌

如果不在已启用 I/O 的运行时中调用,此函数会发生 panic。

当从由 tokio 运行时驱动的 future 中调用此函数时,运行时通常是隐式设置的;否则可以通过 Runtime::enter 函数显式设置运行时。

源代码

pub fn into_std(self) -> Result<TcpListener>

tokio::net::TcpListener 转换为 std::net::TcpListener

返回的 std::net::TcpListener 将 nonblocking 模式设置为 true。如果需要,使用 set_nonblocking 更改阻塞模式。

§示例
use std::error::Error;

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    let tokio_listener = tokio::net::TcpListener::bind("127.0.0.1:0").await?;
    let std_listener = tokio_listener.into_std()?;
    std_listener.set_nonblocking(false)?;
    Ok(())
}
源代码

pub fn local_addr(&self) -> Result<SocketAddr>

返回此监听器绑定的本地地址。

例如,在绑定到端口 0 以找出实际绑定了哪个端口时,这可能很有用。

§示例
use tokio::net::TcpListener;

use std::io;
use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4};

#[tokio::main]
async fn main() -> io::Result<()> {
    let listener = TcpListener::bind("127.0.0.1:8080").await?;

    assert_eq!(listener.local_addr()?,
               SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080)));

    Ok(())
}
源代码

pub fn ttl(&self) -> Result<u32>

获取此套接字的 IP_TTL 选项的值。

有关此选项的更多信息,请参阅 set_ttl

§示例
use tokio::net::TcpListener;

use std::io;

#[tokio::main]
async fn main() -> io::Result<()> {
   let listener = TcpListener::bind("127.0.0.1:0").await?;

   listener.set_ttl(100).expect("could not set TTL");
   assert_eq!(listener.ttl()?, 100);

   Ok(())
}
源代码

pub fn set_ttl(&self, ttl: u32) -> Result<()>

设置此套接字上 IP_TTL 选项的值。

此值设置从此套接字发送的每个数据包中使用的生存时间字段。

§示例
use tokio::net::TcpListener;

use std::io;

#[tokio::main]
async fn main() -> io::Result<()> {
    let listener = TcpListener::bind("127.0.0.1:0").await?;

    listener.set_ttl(100).expect("could not set TTL");

    Ok(())
}

trait 实现§

源代码§

impl AsRawSocket for TcpListener

Available on docsrs, or Windows only.
源代码§

fn as_raw_socket(&self) -> RawSocket

Extracts the raw socket. 更多信息
源代码§

impl AsSocket for TcpListener

Available on docsrs, or Windows only.
源代码§

fn as_socket(&self) -> BorrowedSocket<'_>

借用此套接字。
源代码§

impl Debug for TcpListener

源代码§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

使用给定的格式化器格式化此值。 更多信息
源代码§

impl TryFrom<TcpListener> for TcpListener

源代码§

fn try_from(stream: TcpListener) -> Result<Self, Self::Error>

消耗流,返回 Tokio 的 I/O 对象。

这等效于 TcpListener::from_std(stream)

源代码§

type Error = Error

转换出错时返回的类型。

自动 trait 实现§

blanket 实现§

源代码§

impl<T> Any for T
where T: 'static + ?Sized,

源代码§

fn type_id(&self) -> TypeId

Gets the TypeId of self. 更多信息
源代码§

impl<T> Borrow<T> for T
where T: ?Sized,

源代码§

fn borrow(&self) -> &T

Immutably borrows from an owned value. 更多信息
源代码§

impl<T> BorrowMut<T> for T
where T: ?Sized,

源代码§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. 更多信息
源代码§

impl<T> From<T> for T

源代码§

fn from(t: T) -> T

原样返回参数。

源代码§

impl<T, U> Into<U> for T
where U: From<T>,

源代码§

fn into(self) -> U

调用 U::from(self)

也就是说,此转换是 From<T> for U 实现选择执行的操作。

源代码§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

源代码§

type Error = Infallible

转换出错时返回的类型。
源代码§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

执行转换。
源代码§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

源代码§

type Error = <U as TryFrom<T>>::Error

转换出错时返回的类型。
源代码§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

执行转换。