Tornado http服务器的bind方法
在httpserver.py中,有一个bind
方法,该方法最后的代码是这样的:
sock.bind(sockaddr)
sock.listen(128)
self._sockets[sock.fileno()] = sock
if self._started:
self.io_loop.add_handler(sock.fileno(), self._handle_events,
ioloop.IOLoop.READ)
表示当一个socket连接时,触发ioloop.IOLoop.READ
event ,调用 self._handle_events ,对吗?
但每个客户端都会生成一个新的文件描述符,对吗?
那么ioloop如何通过sock.fileno()来监控客户端的socket连接呢? (httpserver的bind方法只调用一次)
In httpserver.py, there is a bind
method, at the end of this method is the code like this:
sock.bind(sockaddr)
sock.listen(128)
self._sockets[sock.fileno()] = sock
if self._started:
self.io_loop.add_handler(sock.fileno(), self._handle_events,
ioloop.IOLoop.READ)
It means when a socket connected, and trigger ioloop.IOLoop.READ
event , call self._handle_events
, right?
But every client will generate a new file descriptor, right?
So how ioloop monitor client's socket connect via sock.fileno()
? (httpserver's bind method only called once)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我只是快速浏览了一下源代码,它似乎是这样工作的:
Tornado 本身并不监视套接字,它使用
epoll
(Linux) 或 <代码>选择。对 self.io_loop.add_handler 的调用只是在新连接可用时添加回调。客户端连接由
self._handle_events
设置,它为套接字收到的每个新连接创建一个新的HTTPConnection
。每个HTTPConnection
使用的通信套接字是通过调用sock.accept()
创建的新套接字。服务器继续像以前一样在同一套接字上接受连接。总之:
HTTPConnection
对象,并使用单独的套接字进行通信。epoll
或select
将职责传递给操作系统。与客户端的实际通信是由HTTPConnection
对象完成的。我认为要理解的关键是这里的套接字仅用于接受新连接。当使用
sock.accept()
接受连接时,会返回一个用于通信的新套接字,然后将其附加到HTTPConnection
对象。I just had a quick look at the source, and it seems to work like this:
Tornado doesn't monitor the sockets itself, it passes this job onto the operating system, using
epoll
(Linux) orselect
. The call toself.io_loop.add_handler
just adds a callback for when a new connection is available.Client connections are set up by
self._handle_events
, which creates a newHTTPConnection
for each new connection recieved by the socket. The communication socket used by eachHTTPConnection
is a new socket created by callingsock.accept()
. The server continues accepting connections on the same socket as before.so in summary:
self._handle_events
when a new connection is detected on the socket.HTTPConnection
object is created for each client, with a separate socket for communication.epoll
orselect
. The actual communication with the clients is done by theHTTPConnection
objects.I think the key thing to understand, is that the socket here is just used for accepting new connections. When a connection is accepted using
sock.accept()
, this returns a new socket for communication, which is then attached to aHTTPConnection
object.