web聊天室(Tornado-WebSocket实现)
Posted cx59244405
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了web聊天室(Tornado-WebSocket实现)相关的知识,希望对你有一定的参考价值。
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Title</title> 6 </head> 7 <body> 8 <div id="contents" style="height:500px;overflow:auto;background-color: darkgray;"></div> 9 <div> 10 <textarea id="msg"></textarea> 11 <input type="button" value="发送" onclick="sendmsg()"> 12 </div> 13 </body> 14 <script> 15 var ws = new WebSocket("ws://"+location.host+"/chat"); 16 var contents = document.getElementById("contents"); 17 var msg = document.getElementById("msg"); 18 ws.onmessage = function (e) { 19 var msg1 = "<p>"+e.data+"</p>"; 20 contents.innerHTML+=msg1; 21 } 22 function sendmsg() { 23 ws.send(msg.value); 24 msg.value = ""; 25 } 26 </script> 27 </html>
1 # coding:utf-8 2 3 import tornado.web 4 import tornado.ioloop 5 import tornado.httpserver 6 import tornado.options 7 import os 8 import datetime 9 10 from tornado.web import RequestHandler 11 from tornado.options import define, options 12 from tornado.websocket import WebSocketHandler 13 14 define("port", default=8000, type=int) 15 16 class IndexHandler(RequestHandler): 17 def get(self): 18 self.render("chat.html") 19 20 class ChatHandler(WebSocketHandler): 21 22 users = set() # 用来存放在线用户的容器 23 24 def open(self): 25 self.users.add(self) # 建立连接后添加用户到容器中 26 for u in self.users: # 向已在线用户发送消息 27 u.write_message(u"[%s]-[%s]-进入聊天室" % (self.request.remote_ip, datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))) 28 29 def on_message(self, message): 30 for u in self.users: # 向在线用户广播消息 31 u.write_message(u"[%s]-[%s]-说:%s" % (self.request.remote_ip, datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"), message)) 32 33 def on_close(self): 34 self.users.remove(self) # 用户关闭连接后从容器中移除用户 35 for u in self.users: 36 u.write_message(u"[%s]-[%s]-离开聊天室" % (self.request.remote_ip, datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))) 37 38 def check_origin(self, origin): 39 return True # 允许WebSocket的跨域请求 40 41 if __name__ == ‘__main__‘: 42 tornado.options.parse_command_line() 43 app = tornado.web.Application([ 44 (r"/", IndexHandler), 45 (r"/chat", ChatHandler), 46 ], 47 #static_path = os.path.join(os.path.dirname(__file__), "static"), 48 #template_path = os.path.join(os.path.dirname(__file__), "template"), 49 debug = True 50 ) 51 http_server = tornado.httpserver.HTTPServer(app) 52 http_server.listen(options.port,address="0.0.0.0") 53 tornado.ioloop.IOLoop.current().start()
以上是关于web聊天室(Tornado-WebSocket实现)的主要内容,如果未能解决你的问题,请参考以下文章