Python:异步tcp套接字服务器
我正在寻找 http://docs.python.org/library/socketserver.html 尝试使用 python 中的套接字服务器处理异步请求。最下面有一个例子,但没有意义。它说您使用端口 0,它分配了任意未使用的端口。但是,如果客户端不在同一个程序中,您如何知道客户端使用哪个端口呢?我不太明白如何使它有用。
I'm looking http://docs.python.org/library/socketserver.html to try and handle asynchronous requests with the socketserver in python. At the very bottom there is an example, but it doesn't make sense. It says you use port 0 which assigns an arbitrary unused port. But how do you know what port to use for the client if they are not in the same program? I do not quite understand how to make this useful.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
由于客户端与服务器在同一脚本中实现,因此端口是已知的。在现实场景中,您应该为守护程序指定一个端口。除了让您的客户端知道要连接哪个端口之外,您可能还需要知道以便在客户端和服务器之间打开防火墙。
Since the client is implemented in the same script as the server, the port is known. In a real-world scenario, you should specify a port for your daemon. Besides letting your clients know on which port to connect, you may also need to know so that you can open firewalls between your clients and your server.
在您链接的示例中,它们正在获取端口:
但是,如果您认真考虑编写异步处理,那么您确实应该查看 www.twistedmatrix.com :)
In the example you linked, they are fetching the port:
However, you should really be looking at www.twistedmatrix.com if you are serious about writing async handling :)
bind
完成后,您需要检索分配给socketserver
的端口:在本例中,这可能是通过ip, port = server.服务器地址
。任意端口只是如果您想创建服务器而不指定端口:操作系统将分配一个可用端口。
当然还必须有一种方法来指定绑定到哪个端口。
You need to retrieve the port that was assigned to the
socketserver
once thebind
is done: in this case, this will probably be throughip, port = server.server_address
.The arbitrary port is just if you want to create a server without specifying a port: the OS will assign an available port.
Of course there must also be a way to specify which port to bind to.
PORT 值 0 表示“我不关心它是什么端口号”,因此 server_address 的
port
值由 ThreadedTCPServer() 调用分配。它不为零。稍后,您将该port
值传递给使用它的客户端。The PORT value 0 says "I don't care what port number it is," so the server_address's
port
value is assigned by the ThreadedTCPServer() call. It is not zero. Later, you pass thatport
value to the client, who uses it.