WebSocket实现动态可视化(一)
实现思路: 服务端向客户端发送数据,客户端接收数据保存为数组,并赋值到echart对应的data值 以下是服务端用websocket向客户端发送数据
服务端
import asyncio
import time
import websockets
async def echo(websocket, path):
for message in range(100):
time.sleep(1)
await websocket.send(str(message))
asyncio.get_event_loop().run_until_complete(websockets.serve(echo, 'localhost', 8765))
asyncio.get_event_loop().run_forever()
客户端
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>消息接收</title>
</head>
<body>
<div id="msg"></div>
<script>
window.onload = function () {
if ("WebSocket" in window) {
ws = new WebSocket("ws://127.0.0.1:8765/");
ws.onopen = function () {
alert('连接成功')
};
ws.onmessage = function (evt) {
var received_msg = evt.data;
document.getElementById('msg').innerText = received_msg
};
ws.onclose = function () {
alert("连接已关闭...");
};
} else {
alert("您的浏览器不支持 WebSocket!");
}
}
</script>
</body>
</html>
总结:
实现的效果就如计数器一样,针对之前ajax轮询,通过websocket可以减少一些不必要的无效请求
|