vue前端后端实现WebScoket 即时通讯和主动断开链接
前端
code.vue
<template>
<div>
<div>about2</div>
</div>
</template>
<script>
export default {
name: 'About2',
components: {},
data() {
return {
lockReconnect: false,
timeout: 2000,
reTimeout: 1000 * 10,
timeoutTimer: null,
reTimeoutTimer: null,
webSocket: null
}
},
mounted() {
this.createWebSocket()
},
methods: {
heartCheckStart() {
if (this.timeoutTimer) {
clearTimeout(this.timeoutTimer)
this.timeoutTimer = null
}
this.timeoutTimer = setTimeout(() => {
try {
this.webSocket.send('heartBeat')
} catch {
if (this.timeoutTimer) {
clearTimeout(this.timeoutTimer)
this.timeoutTimer = null
}
}
}, this.timeout)
},
heartCheckReset() {
clearTimeout(this.timeoutTimer)
this.timeoutTimer = null
this.heartCheckStart()
},
createWebSocket() {
if (window && 'WebSocket' in window) {
this.webSocket = new WebSocket('ws://localhost:5002')
}
this.webSocket.onopen = () => {
this.heartCheckStart()
}
this.webSocket.onerror = () => {
this.reConnect()
}
this.webSocket.onmessage = (event) => {
console.log('响应数据-event', event.data)
if (JSON.parse(event.data) instanceof Object && JSON.parse(event.data).code === 0) {
this.webSocket.close()
this.lockReconnect = false
return
} else {
this.heartCheckReset()
}
}
this.webSocket.onclose = (event) => {
if (event.code === 1005) return
this.reConnect()
}
},
reConnect() {
if (this.lockReconnect) {
return
}
this.lockReconnect = true
this.reTimeoutTimer && clearTimeout(this.reTimeoutTimer)
this.reTimeoutTimer = setTimeout(() => {
this.createWebSocket()
this.lockReconnect = false
}, this.reTimeout)
}
}
}
</script>
<style lang="scss" scoped></style>
效果
后端
index.js
const WebScoket = require("ws");
const ws = new WebScoket.Server({
port: 5002,
});
ws.on('connection',ws=>{
console.log("server-connection");
let progress = 0;
let code = 200
ws.on("message",msg=>{
console.log("服务器接受的消息:",msg);
setTimeout(()=>{
progress += 20
},500)
console.log("progress", progress);
if ( progress > 100 ) {
code = 0
}
let data = {
code : code,
data:[1,2,3],
progress: progress,
}
ws.send(JSON.stringify(data))
})
ws.send('链接已建立')
})