WebSocket
可以保持着浏览器和客户端之间的长连接, 通过
WebSocket
可以实现数据由后端推送到前端(并不局限于前端一直请求),保证了数据传输的实时性.
WebSocket
涉及到前端代码和后端代码的改造
起步 webSocket 小样
安装
WebSocket
包
npm i ws - S
创建 WebSocket 实例对象 并且监听事件(模拟 app.js)
const WebSocket = require("ws")
// 创建出WebSocket实例对象
const wss = new WebSocket.Server({
port: 9998
})
// 监听事件
wss.on("connection", client => {
console.log("服务器连接成功了")
client.on("message", msg => {
console.log("客户端发送数据过来了")
// 发送数据给客户端
client.send(msg)
})
})
node app.js 启动 前端按钮才生效
前端测试html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<button id="connect">链接</button>
<button id="send" disabled="true">发送数据</button>
从服务端接收数据如下 <br>
<span id="recv"></span>
<script>
let connect = document.querySelector('#connect')
let send = document.querySelector('#send')
let recv = document.querySelector('#recv')
let ws = null
connect.onclick = function () {
ws = new WebSocket('ws://localhost:9998')
ws.onopen = () => {
console.log('服务器链接成功了')
send.disabled = false
}
ws.onclose = () => {
console.log('链接服务器失败')
send.disabled = true
}
ws.onmessage = msg => {
console.log('接收到从服务器端发来的数据了')
console.log(msg)
recv.innerHTML = msg.data
}
}
send.onclick = function () {
ws.send(JSON.stringify({
action:'fullScreen',
socketType:'fullScreen',
chartName: 'trend',
value:'true'
}))
}
</script>
</body>
</html>