目录
方式二、服务端开启http 和 ws 的api,脚本向发送http请求触发ws的推送
零、基本信息
一、一对一长连接
一对一解释:由于只有在接收信息的时候触发服务端消息的发送,所以只实现了一对一的消息触发
1-1 server 端
from tornado import ioloop from tornado.web import Application from tornado.websocket import WebSocketHandler class EchoWebSocket(WebSocketHandler): def open(self): print("WebSocket opened") # 处理client发送的数据 def on_message(self, message): print(message) # 将数据发送给连接的client self.write_message(u"server said: " + message) def on_close(self): print("WebSocket closed") # 允许所有跨域通讯,解决403问题 def check_origin(self, origin): return True if __name__ == "__main__": application = Application([ (r"/", EchoWebSocket), ]) application.listen(8080) ioloop.IOLoop.current().start()
1-2 client 端
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Tornado Websocket</title> </head> <body> <body onload='onLoad();'> Message to send: <input type="text" id="msg"/> <input type="button" onclick="sendMsg();" value="发送"/> </body> </body> <script type="text/javascript"> var ws; function onLoad() { ws = new WebSocket("ws://localhost:8080/"); ws.onmessage = function (e) { // alert(e.data) console.log(e.data) } } function sendMsg() { ws.send(document.getElementById('msg').value); } </script> </html>