一、效果展示
二、具体实现
1、后端实现
-
创建express项目
-
安装websocket依赖包
npm i ws
- 在src/service目录下创建web_socket_service.js
const WebSocket=require('ws')
//创建WebSocket服务端的对象,绑定的端口号是9998
const wss=new WebSocket.Server({
port:9998
})
module.exports.listener=()=>{
//对客户端连接事件进行监听,client代表的是客户端的连接的socket对象
wss.on('connection',client=>{
console.log('有客户端连接成功了');
//对客户端的连接对象进行message事件的监听
//msg:由客户端发给服务端的数据
client.on('message',msg=>{
console.log('客户端发送给服务器端',msg);
let data=[
[100, 150, 120, 90, 30, 130, 110],
[100, 150, 120, 90, 40, 120, 112],
[100, 150, 120, 90, 70, 133, 115],
[100, 150, 120, 90, 80, 110, 110],
[100, 150, 120, 90, 100, 140, 115],
[100, 150, 120, 90, 90, 150, 120],
[100, 150, 120, 90, 80, 120, 160],
[100, 150, 120, 90, 70, 160, 165],
[100, 150, 120, 90, 60, 140, 166],
[100, 150, 120, 90, 50, 110, 145],
]
let i=0
setInterval(() => {
if(i==data.length){
i=0
}
client.send(JSON.stringify(data[i]))
i++
}, 1000);
//由服务端往客户端发送数据
})
})
}
- 在app.js文件中引入
const express=require('express')
const app=express()
const port=3000
app.get('/',(req,res)=>res.send('hello express'))
app.use('/',express.static("public"))
app.use(express.json())
app.listen(port,()=>{console.log('server is running,port is'+port);})
const websocketservice=require('./service/web_socket_service')
websocketservice.listener()
2、前端实现
- 安装echarts依赖包
yarn add echarts
- 创建App.jsx组件,编写echarts代码
import React, { Component, createRef } from 'react'
import * as echarts from 'echarts'
export default class App extends Component {
constructor() {
super()
this.containerRef = createRef()
}
componentDidMount() {
let options = {
title: {
text: '销售量统计'
},
xAxis: {
data: ['冰淇淋', '面包', '巧克力', '矿泉水', '方便面', '饼干', '锅巴']
},
yAxis: {},
series: [
{
name: '销量',
type: 'line',
data: [100, 150, 120, 90, 30, 130, 110]
}
]
}
let mychart = echarts.init(this.containerRef.current)
const ws = new WebSocket('ws://localhost:9998')
ws.onopen = () => {
console.log('连接服务器端成功');
ws.send(1)
}
ws.onerror = () => {
console.log('连接服务器失败');
}
ws.onmessage = (msg) => {
console.log('接收到服务端发送的数据');
console.log(JSON.parse(msg.data));
options.series[0].data = JSON.parse(msg.data)
mychart.setOption(options)
}
}
render() {
return (
<div>
<div ref={this.containerRef} style={{ width: '500px', height: '500px' }}></div>
</div>
)
}
}