Python创建多个线程分别启动http、WebSocket服务-/lib/WebSocketServer.py

时间:2024-10-15 09:40:11
import tornado.web
import tornado.httpserver
import tornado.ioloop
import tornado.websocket

class WebSocketHandler(tornado.websocket.WebSocketHandler):
    def open(self):
        print('WebSocket opened')

    def on_message(self, message):
        print('WebSocket message received {}'.format(message))
        self.write_message(message)

    def on_close(self):
        print('WebSocket closed')

    def check_origin(self, origin):
        return True

class WebSocketServer:
    def __init__(self, port):
        self.port = port
    def start(self):
        application = tornado.web.Application([(r'/websocket', WebSocketHandler)])
        http_server = tornado.httpserver.HTTPServer(application)
        http_server.listen(self.port)
        tornado.ioloop.IOLoop.instance().start()