上节链接:WebSocket实现动态可视化(二) 上节已经实现了图表的可视化,但还有优化的地方,如x轴未实现动态,为死数据,且websocket一旦连接还未实现主动断开的操作,所以该篇文章针对这两点做优化处理。
服务端
import random
from flask import Flask
from flask_sockets import Sockets
import datetime
import time
from gevent import pywsgi
from geventwebsocket.handler import WebSocketHandler
app = Flask(__name__)
sockets = Sockets(app)
@sockets.route('/test')
def test(ws):
while not ws.closed:
message = ws.receive()
if message:
local_time = time.strftime("%H:%M:%S", time.localtime())
info = random.randint(1, 10)
msg = {"x": local_time, "y": info}
time.sleep(1)
ws.send(str(msg))
else:
print('连接断开')
break
if __name__ == "__main__":
server = pywsgi.WSGIServer(('0.0.0.0', 5001), application=app,handler_class=WebSocketHandler)
print('服务已开启')
server.serve_forever()
客户端
<template>
<div>
<el-breadcrumb separator-class="el-icon-arrow-right">
<el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
<el-breadcrumb-item>图表</el-breadcrumb-item>
</el-breadcrumb>
<el-card>
<div ref="seller" style="height: 260px; width: 600px; background: rgb(255, 255, 255)" id="msg"></div>
<el-button type="success" @click="initWebSocket">点击</el-button>
<el-button type="success" @click="websocketautoclose">停止</el-button>
</el-card>
</div>
</template>
<script>
export default {
data() {
return {
xAxisList: [],
yAxisList: [],
}
},
mounted() {
this.initChart()
this.updateChart()
},
methods: {
initChart() {
this.chart = this.$echarts.init(this.$refs.seller)
},
updateChart() {
const option = {
dataZoom: [
{
show: true,
realtime: true,
start: 0,
end: 100,
xAxisIndex: [0, 1]
},
{
type: 'inside',
realtime: true,
start: 0,
end: 100,
xAxisIndex: [0, 1]
}
],
xAxis: {
type: 'category',
data: this.xAxisList,
},
yAxis: {
type: 'value'
},
series: [
{
data: this.yAxisList,
type: 'line',
smooth: true
}
]
};
this.chart.setOption(option)
},
initWebSocket() {
let wsuri = 'ws://192.168.1.20:5000/test'
this.ws = new WebSocket(wsuri)
this.ws.onmessage = this.websocketonmessage
this.ws.onopen = this.websocketonopen
this.ws.onerror = this.websocketonerror
this.ws.onclose = this.websocketclose
this.yAxisList = []
this.yAxisList = []
},
websocketonopen() {
console.log('连接 websocket 成功')
this.ws.send('test')
},
websocketonmessage(e) {
let msg = eval("("+e.data+")")
console.log(msg)
this.yAxisList.push(msg.y)
this.xAxisList.push(msg.x)
this.updateChart()
this.ws.send('test')
if (!document.getElementById("msg")) {
this.websocketautoclose()
alert('服务已断开,请保持在图表页面')
}
},
websocketonerror() {
this.initWebSocket()
},
websocketclose(e) {
console.log('断开连接', e)
},
websocketautoclose() {
this.ws.close()
},
}
}
</script>
<style lang="less" scoped>
</style>
实现效果
小结:
该篇文章已基本实现图表动态可视化,后面如想到有更好的方法再优化处理,有错误或不懂的,以及需要完整源码的可私我,共同进步!
|