Server 部分,主要就是继承 WebSocketHandler 实现了个 WebSocket Handler
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 logging import tornado.web import tornado.websocket import tornado.ioloop import tornado.options
from tornado.options import define, options
define("port", default=3000, help="run on the given port", type=int)
class Application(tornado.web.Application): def __init__(self): handlers = [(r"/", MainHandler)] settings = dict(debug=True) tornado.web.Application.__init__(self, handlers, **settings)
class MainHandler(tornado.websocket.WebSocketHandler): def check_origin(self, origin): return True
def open(self): logging.info("A client connected.")
def on_close(self): logging.info("A client disconnected")
def on_message(self, message): logging.info("message: {}".format(message))
def main(): tornado.options.parse_command_line() app = Application() app.listen(options.port) tornado.ioloop.IOLoop.instance().start()
if __name__ == "__main__": main()
|
Client 部分
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 42 43 44 45 46 47
|
from tornado.ioloop import IOLoop, PeriodicCallback from tornado import gen from tornado.websocket import websocket_connect
class Client(object): def __init__(self, url, timeout): self.url = url self.timeout = timeout self.ioloop = IOLoop.instance() self.ws = None self.connect() PeriodicCallback(self.keep_alive, 20000).start() self.ioloop.start()
@gen.coroutine def connect(self): print("trying to connect") try: self.ws = yield websocket_connect(self.url) except Exception as e: print("connection error") else: print("connected") self.run()
@gen.coroutine def run(self): while True: msg = yield self.ws.read_message() if msg is None: print("connection closed") self.ws = None break
def keep_alive(self): if self.ws is None: self.connect() else: self.ws.write_message("keep alive")
if __name__ == "__main__": client = Client("ws://localhost:3000", 5)
|
运行 Server 和 Clinet 之后输出如下:
1 2 3 4 5
| [I 220805 10:49:12 server:27] A client connected. [I 220805 10:49:32 server:33] message: keep alive [I 220805 10:49:52 server:33] message: keep alive [I 220805 10:50:12 server:33] message: keep alive [I 220805 10:50:13 server:30] A client disconnected
|
1 2
| trying to connect connected
|