tornado的websocket
参考
http://www.tuicool.com/articles/niuqiiA
http://www.docin.com/p-278084273.html
http://www.tuicool.com/articles/QniyIz
客户端:
index.html
<html> <head> <script type="text/javascript"> var ws = new WebSocket("ws://182.254.155.153:8000/chat"); ws.onmessage = function(event) { console.log(event); } ws.onopen = function() { console.log('open'); }; ws.onclose = function() { console.log('Closed! '); } function send() { ws.send(document.getElementById('chat').value ); } </script> </head> <body> <div> hello <input id="chat"> <button onclick="send()">send</button> </div> </body> </html>
服务端:
#!/usr/bin/python #coding:utf-8 import os.path import tornado.httpserver import tornado.web import tornado.ioloop import tornado.options import tornado.httpclient import tornado.websocket import json class IndexHandler(tornado.web.RequestHandler): def get(self): self.render("index.html") class SocketHandler(tornado.websocket.WebSocketHandler): """docstring for SocketHandler""" clients = set() @staticmethod def send_to_all(message): for c in SocketHandler.clients: c.write_message(json.dumps(message)) def open(self): self.write_message(json.dumps({ 'type': 'sys', 'message': 'Welcome to WebSocket', })) SocketHandler.send_to_all({ 'type': 'sys', 'message': str(id(self)) + ' has joined', }) SocketHandler.clients.add(self) def on_close(self): SocketHandler.clients.remove(self) SocketHandler.send_to_all({ 'type': 'sys', 'message': str(id(self)) + ' has left', }) def on_message(self, message): SocketHandler.send_to_all({ 'type': 'user', 'id': id(self), 'message': message, }) ##MAIN if __name__ == '__main__': app = tornado.web.Application( handlers=[ (r"/", IndexHandler), (r"/chat", SocketHandler) ], debug = True, # template_path = os.path.join(os.path.dirname(__file__), "templates"), # static_path = os.path.join(os.path.dirname(__file__), "static") ) app.listen(8000) tornado.ioloop.IOLoop.instance().start()
apt-getinstallpython-virtualenv
相关推荐
hjhmpl 2020-06-14
selectY 2020-07-18
zhangxuelong 2020-06-14
zhangxuelong 2020-06-14
牧码人 2020-06-14
thundor 2020-05-05
Cagey 2020-04-25
KarlDoenitz 2020-04-16
牧码人 2020-01-25
KarlDoenitz 2019-12-28
hjhmpl 2019-12-25
hjhmpl 2019-12-17
selectY 2019-12-11
KarlDoenitz 2019-12-06
selectY 2019-12-05
Cagey 2019-12-05
hjhmpl 2019-11-03
牧码人 2019-11-03
chenzhanhai 2019-04-09