tornado add_socket 与listen 的区别
时间: 2024-03-21 17:40:55 浏览: 52
`add_socket` 和 `listen` 都是 Tornado 框架中用来启动服务的方法,但是它们的作用略有不同。
`listen` 是 Tornado 服务器启动的主要方法,它会创建一个 `HTTPServer` 对象,并绑定一个端口(可以是一个整数或者一个 `socket` 对象),然后开始监听客户端请求。例如:
```python
import tornado.ioloop
import tornado.web
class MainHandler(tornado.web.RequestHandler):
def get(self):
self.write("Hello, world")
if __name__ == "__main__":
app = tornado.web.Application([(r"/", MainHandler)])
app.listen(8888)
tornado.ioloop.IOLoop.current().start()
```
上面的代码中,我们通过 `app.listen(8888)` 启动了 Tornado 服务器,并绑定了 8888 端口。
`add_socket` 则是在 Tornado 服务器已经启动之后,动态地添加一个新的监听端口。例如:
```python
import tornado.ioloop
import tornado.web
import socket
class SecondHandler(tornado.web.RequestHandler):
def get(self):
self.write("Hello, world from second listener")
if __name__ == "__main__":
app = tornado.web.Application([(r"/", MainHandler), (r"/second", SecondHandler)])
app.listen(8888)
# 添加一个新的监听端口
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)
sock.bind(('localhost', 8889))
sock.listen(128)
app.add_socket(sock)
tornado.ioloop.IOLoop.current().start()
```
上面的代码中,我们启动了一个 Tornado 服务器,并绑定了 8888 端口。然后,我们通过创建一个新的 `socket` 对象,并将其绑定到 8889 端口,再通过 `app.add_socket(sock)` 方法将其添加到 Tornado 服务器中。这样,我们就成功地为 Tornado 服务器添加了一个新的监听端口。
因此,`listen` 和 `add_socket` 的主要区别在于,`listen` 是用来启动 Tornado 服务器的,而 `add_socket` 则是用来在运行过程中动态地添加一个新的监听端口的。
阅读全文
相关推荐


















