使用tornad时如何用多处理绑定多个端口

2024-05-15 03:40:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我的python版本是3.4,tornado版本是4.3。 我有两个服务器,它们必须在运行时共享一些数据,我的代码是这样的

from tornado.web import gen, asynchronous, RequestHandler, Application
from tornado.httpserver import HTTPServer
from tornado.ioloop import IOLoop


class HelloHandler(RequestHandler):
    @asynchronous
    @gen.engine
    def get(self):
        self.write('hello')
        self.finish()


class MainHandler(RequestHandler):
    @asynchronous
    @gen.engine
    def get(self):
        self.write('main')
        self.finish()


helloApp = Application([
    (r'/hello', HelloHandler),
])

mainApp = Application([
    (r'/main', MainHandler),
])

if __name__ == "__main__":
    hello_server = HTTPServer(helloApp)
    hello_server.bind(8881)
    hello_server.start()
    # hello_server.start(0)
    main_server = HTTPServer(mainApp)
    main_server.bind(8882)
    main_server.start()
    # main_server.start(0)
    IOLoop.current().start()

它可以工作,但是当我试图通过使用服务器启动(0),我收到一个错误:'OSError:[Errno 98]地址已在使用中,我已经使用了不同的端口(8881,8882)。这是怎么发生的? 怎么解决呢?在


Tags: fromimportself版本服务器helloserverapplication
1条回答
网友
1楼 · 发布于 2024-05-15 03:40:31

start(n)仅适用于单个服务器。要使用多个,必须分别使用bind_socketsfork_processes和{}(示例改编自http://www.tornadoweb.org/en/stable/tcpserver.html):

from tornado.netutil import bind_sockets

hello_sockets = bind_sockets(8881)
main_sockets = bind_sockets(8882)
tornado.process.fork_processes(0)
hello_server = HTTPServer(helloApp)
hello_server.add_sockets(hello_sockets)
main_server = HTTPServer(mainApp)
main_server.add_sockets(main_sockets)
IOLoop.current().start()

相关问题 更多 >

    热门问题