本文写的是基于Python+Tornado实现Websocket的demo,直接复制下来就可使用。
缺包的话,直接pip安装即可。
# -*- coding: utf-8 -*-
"""
tornado websocket
author: cjh
"""
import json
from tornado.ioloop import IOLoop
from tornado.web import Application
from tornado.websocket import WebSocketHandler
class WebsocketBase(WebSocketHandler):
"""继承WebSocketHandler基类,重写所需实例方法"""
def on_message(self, message):
"""接收消息"""
def data_received(self, chunk):
"""接收消息"""
def open(self):
"""新的websocket连接后被调动"""
print 'new_connect', self
def on_close(self):
"""websocket连接关闭后被调用"""
print 'lost_connect', self
def check_origin(self, origin):
"""重写同源检查 解决跨域问题"""
return True
class RealData(WebsocketBase):
"""实时数据"""
def on_message(self, args):
"""args 是请求参数"""
# TODO 实际的业务操作,只需在此处写自己的业务逻辑即可。
self.write_message('啦啦啦') # 向客户端返回数据,如果是字典、列表这些数据类型,需要json.dumps()
class WebSocketApplication(Application):
def __init__(self):
handlers = [
(r'/real_data', RealData), # websocket路由
]
Application.__init__(self, handlers)
def run():
app = WebSocketApplication()
app.listen(port=4053, address='0.0.0.0')
IOLoop.current().start()
if __name__ == "__main__":
run()
自己本地起了websocket服务后,该如可测试呢?下面附一个简单的前端小脚本,复制下来存为html文件,直接浏览器打开,F12后即可自己调试啦。
<html>
<head>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script type="text/javascript">
window.onload = function() {
var ws = new WebSocket("ws://127.0.0.1:4053");
ws.onopen = function() {
console.log("client:打开连接");
ws.send("{'unit_id':'38', 'db_code': 'sx'}");
};
ws.onmessage = function(e) {
console.log("client:接收到服务端的消息 " + e.data);
setTimeout(() => {
/*ws.close(); */
}, 5000);
};
ws.onclose = function(params) {
console.log("client:关闭连接");
};
}
</script>
</head>
<body>
<h1>Ping output:</h1>
<pre id="output">
</pre>
</body>
</html>