1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
| import uuid
import tornado.httpserver import tornado.ioloop import tornado.web import tornado.websocket
clients = []
class WebSocketHandler(tornado.websocket.WebSocketHandler): def open(self): self.clientid = str(uuid.uuid4()) print("WebSocket opened:"+self.clientid) clients.append(self)
def on_message(self, message): if type(message) == str: print("Message received: {}".format(message)) self.write_message("You said: " + message) elif type(message) == bytes: print("字节类型数据,长度为:", len(message))
def on_close(self): print("WebSocket closed:"+self.clientid) clients.remove(self)
def check_origin(self, origin): return True
app = tornado.web.Application([(r"/ws", WebSocketHandler)])
server = tornado.httpserver.HTTPServer(app)
def start_ws_server(): server.listen(8081) tornado.ioloop.IOLoop.instance().start()
|