基于Tornado的websocket实现聊天室
Posted jintian
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了基于Tornado的websocket实现聊天室相关的知识,希望对你有一定的参考价值。
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>
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()
以上是关于基于Tornado的websocket实现聊天室的主要内容,如果未能解决你的问题,请参考以下文章
如何在 Tornado 中创建多个 websocket 聊天?
tornado+websocket+mongodb实现在线视屏文字聊天
把酒言欢话聊天,基于Vue3.0+Tornado6.1+Redis发布订阅(pubsub)模式打造异步非阻塞(aioredis)实时(websocket)通信聊天系统