上节链接:WebSocket实现动态可视化(一) 上节实现了用websocket实现了计时器的效果,这节直接实现图表的动态可视化 前端:Vue 后端:python 图表:echart
服务端
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):
for message in range(8):
msg = random.randint(1, 10)
time.sleep(1)
ws.send(str(msg))
print(msg)
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)"></div>
<el-button type="success" @click="initWebSocket">点击</el-button>
<div id="msg"></div>
</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: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
},
yAxis: {
type: 'value'
},
series: [
{
data: this.yAxisList,
type: 'line',
smooth: true
}
]
};
this.chart.setOption(option)
},
initWebSocket() {
let wsuri = 'ws://127.0.0.1:5001/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 = []
},
websocketonopen() {
console.log('连接 websocket 成功')
},
websocketonmessage(e) {
let msg = e.data
this.yAxisList.push(msg)
this.xAxisList =
console.log(this.yAxisList)
this.updateChart()
},
websocketonerror() {
this.initWebSocket()
},
websocketclose(e) {
console.log('断开连接', e)
},
}
}
</script>
实现效果
小结:
对于Vue的运用在这里有许多涉及的,在此不讲太多,有错误或不懂的可私聊,看到即回复!
|