1.app.py
#!/usr/bin/env python # -*- coding:utf-8 -*- import uuid import json import tornado.ioloop import tornado.web import tornado.websocket class IndexHandler(tornado.web.RequestHandler): def get(self): self.render('index.html') class ChatHandler(tornado.websocket.WebSocketHandler): # 用户存储当前聊天室用户 waiters = set() # 用于存储历时消息 messages = [] def open(self): """ 客户端连接成功时,自动执行 :return: """ ChatHandler.waiters.add(self) uid = str(uuid.uuid4()) self.write_message(uid) for msg in ChatHandler.messages: content = self.render_string('message.html', **msg) self.write_message(content) def on_message(self, message): """ 客户端连发送消息时,自动执行 :param message: :return: """ msg = json.loads(message) ChatHandler.messages.append(msg) for client in ChatHandler.waiters: content = client.render_string('message.html', **msg) client.write_message(content) def on_close(self): """ 客户端关闭连接时,,自动执行 :return: """ ChatHandler.waiters.remove(self) def run(): settings = { 'template_path': 'templates', 'static_path': 'static', } application = tornado.web.Application([ (r"/", IndexHandler), (r"/chat", ChatHandler), ], **settings) application.listen(8888,address='0.0.0.0') tornado.ioloop.IOLoop.instance().start() if __name__ == "__main__": run()
2.message.html
<div style="border: 1px solid #dddddd;margin: 10px;"> <div>游客{{uid}}</div> <div style="margin-left: 20px;">{{message}}</div> </div>
3.index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Python聊天室</title> </head> <body> <div> <input type="text" id="txt"/> <input type="button" id="btn" value="提交" onclick="sendMsg();"/> <input type="button" id="close" value="关闭连接" onclick="closeConn();"/> </div> <div id="container" style="border: 1px solid #dddddd;margin: 20px;min-height: 500px;"> </div> <script src="/static/jquery-2.1.4.min.js"></script> <script type="text/javascript"> $(function () { wsUpdater.start(); }); var wsUpdater = { socket: null, uid: null, start: function() { var url = "ws://192.168.20.200:8888/chat"; wsUpdater.socket = new WebSocket(url); wsUpdater.socket.onmessage = function(event) { if(wsUpdater.uid){ wsUpdater.showMessage(event.data); }else{ wsUpdater.uid = event.data; } } }, showMessage: function(content) { $('#container').append(content); } }; function sendMsg() { var msg = { uid: wsUpdater.uid, message: $("#txt").val() }; wsUpdater.socket.send(JSON.stringify(msg)); } </script> </body> </html>
4.引入jQuery