我想在同一个IOLoop中运行TCPServer
和tornado.web.Application
。我想使用TCPServer来处理IPC。我以通常的方式初始化所有内容:
tcpServer = TCPServer()
tcpServer.listen(8888,address="127.0.0.1")
tornado.options.parse_command_line()
app=Application()
server=tornado.httpserver.HTTPServer(app)
server.listen(8000)
tornado.ioloop.IOLoop.current().start()
如何在tornado.web.Application
内拨打电话来调用TCPServer方法?
答案 0 :(得分:1)
您可以将TCPServer实例传递给Application(甚至可以在其中创建)。下面是处理程序的简单示例:
import tornado.ioloop
import tornado.httpserver
import tornado.options
from tornado.web import RequestHandler, Application
from tornado.tcpserver import TCPServer
tcpServer = TCPServer()
tcpServer.listen(8888,address="127.0.0.1")
class MainHandler(RequestHandler):
def get(self):
if self.request.uri == '/stop':
self.write("tcpserver stopped")
self.application.tcp_server.stop()
else:
self.write("go to /stop tcpserver")
class CustomApp(Application):
def __init__(self, tcp_server, *args, **kwargs):
super(CustomApp, self).__init__(*args, **kwargs)
self.tcp_server = tcp_server
# self.tcp_server.some_method...
self.add_handlers(r"^.*$", [(r"/.*", MainHandler)])
tornado.options.parse_command_line()
app=CustomApp(tcpServer)
server=tornado.httpserver.HTTPServer(app)
server.listen(8000)
tornado.ioloop.IOLoop.current().start()
如果需要通过TCP从Application调用该服务器,而不是直接调用逻辑,则可以使用TCPClient。