self.render-string() 渲染成字符串
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> .container{ border: 2px solid #dddddd; height: 400px; overflow: auto; } </style> </head> <body> <div style="width: 750px;margin: 0 auto;"> <h1>1024聊天室</h1> <div class="container"> </div> <div class="input"> <input type="text" id="txt" /> <input type="button" value="发送" id="btn" onclick="sendMessage();" /> </div> </div> <script src="/static/jquery-1.12.4.js"></script> <script> ws = new WebSocket("ws://127.0.0.1:8888/chat"); ws.onmessage = function (event) { $(‘.container‘).append(event.data); }; ws.onclose = function () { }; function sendMessage() { ws.send($(‘#txt‘).val()); } </script> </body> </html>
index.html
import tornado.web import tornado.ioloop import tornado.websocket class IndexHandler(tornado.web.RequestHandler): def get(self, *args, **kwargs): self.render(‘index.html‘) users = set() class ChatHandler(tornado.websocket.WebSocketHandler): def open(self, *args, **kwargs): """ 客户端和服务端已经建立连接 1. 连接 2. 握手 :param args: :param kwargs: :return: """ users.add(self) def on_message(self, message): content = self.render_string(‘message.html‘,msg=message) for client in users: client.write_message(content) def on_close(self): """ 客户端主动关闭连接 :return: """ users.remove(self) def run(): settings = { ‘template_path‘: ‘templates‘, ‘static_path‘: ‘static‘, } application = tornado.web.Application([ (r"/", IndexHandler), (r"/chat", ChatHandler), ], **settings) application.listen(8888) tornado.ioloop.IOLoop.instance().start() if __name__ == "__main__": run()
app.py
原文地址:https://www.cnblogs.com/jintian/p/11445360.html
时间: 2024-10-31 00:58:02