是否可以在Tokio中关闭TcpListener? [英] Is it possible to close a TcpListener in Tokio?
问题描述
我创建了一个tokio_core::net::TcpListener
,然后调用incoming
方法以获取传入连接流.然后,我在该流上使用for_each
方法将其转换为Future,并在事件循环上运行Future.一旦这样做,以后是否有任何方法可以解除与端口的绑定?
I have a tokio_core::net::TcpListener
that I create and then call the incoming
method on to get a stream of incoming connections. I then use the for_each
method on that stream to turn it into a future and run the future on an event loop. Once I do that is there any way to unbind from the port at some later time?
如果没有,那么Tokio中是否还有其他API可用于创建可以关闭的TCP服务器?
If not, is there any other API in Tokio that can be used to create a TCP server which can be closed?
推荐答案
简而言之,您需要删除TcpListener
/for_each
返回的Future
.
In short, you need to drop the TcpListener
/ the Future
returned by for_each
.
您可以:
-
为某些包含应用程序其余状态的结构编写
Future
实现.然后,结构的Future::poll
实现poll
包含所有包含的Future
状态,如果您想提早退出,则返回Async::Ready
.如果将包含的Future
包装在
Write a
Future
implementation for some struct containing the rest of your application's state. TheFuture::poll
implementation for your struct thenpoll
s all the containedFuture
states, and returnsAsync::Ready
if you want to exit early. It might help performance if the containedFuture
s are wrapped inoneshot::spawn
to run in their own task.
您的结构将包含Option<SpawnHandle<(), ...>>
.如果您想停止收听,只需将其设置为None
.
Your struct would contain an Option<SpawnHandle<(), ...>>
. If you want to stop listening just set it to None
.
后两种方法仅在看到/处理传入的连接后停止,因此它们仅在繁忙的环境中工作.
The latter two methods only stop after seeing/handling an incoming connection, so they only work in a busy environment.
这篇关于是否可以在Tokio中关闭TcpListener?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!