tornado是什么
Tornado是一个轻量级的Web框架,异步非阻塞+内置WebSocket功能。
安装:pip3 install tornado
tornado websocket示例
import tornado from tornado.web import Application from tornado.web import RequestHandler from tornado.websocket import WebSocketHandler class IndexHandler(RequestHandler): def get(self, *args, **kwargs): # self.write('Hello World') self.render('index.html') def post(self, *args, **kwargs): user = self.get_argument('user') self.write('成功') WS_LIST = [] class MessageHandler(WebSocketHandler): def open(self, *args, **kwargs): WS_LIST.append(self) def on_message(self, message): for ws in WS_LIST: ws.write_message(message) def on_close(self): WS_LIST.remove(self) settings = { 'template_path': 'templates', 'static_path': 'static', } app = Application([ (r"/index", IndexHandler), (r"/message", MessageHandler), ], **settings) if __name__ == '__main__': app.listen(address='0.0.0.0', port=9999) tornado.ioloop.IOLoop.instance().start()
前端页面:
<!DOCTYPE html> <html lang="zh-cn"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Title</title> <style> .msg-item{ padding: 5px; border: 1px; margin: 0 5px; } </style> </head> <body> <h1>首页</h1> <div> <h2>发送消息</h2> <input id="msg" type="text" /> <input type="button" value="发送" onclick="sendMsg()"> <h2>接收消息</h2> <div id="container"> </div> </div> <script src="/static/jquery-3.3.1.min.js"></script> <script> ws = new WebSocket('ws://192.168.12.42:9999/message'); ws.onmessage = function (event) { var tag = document.createElement('div'); tag.className = 'msg-item'; tag.innerText = event.data; $('#container').append(tag); } ws.onclose = function (event) { // 服务端主动断开了连接 } function sendMsg() { ws.send($('#msg').val()); } // 客户端要断开连接 // ws.close() </script> </body> </html>