前段时间项目里有用到ws长连接,今天抽空记录一下。
// webSocket.js
export function webSocket(v) {
let socketUrl = null
let heartTime = null
if (typeof WebSocket === 'undefined') {
// 判断当前浏览器是否支持websocket通信
// 目前,支持WebSocket的主流浏览器如下:
// Chrome
// Firefox
// IE >= 10
// Sarafi >= 6
// Android >= 4.4
// iOS >= 8
v.$notify({
title: '提示',
message: '当前浏览器无法接收实时消息,请使用谷歌或者IE10以上版本浏览器!',
type: 'warning',
duration: 0
})
}else {
const host = window.location.host
const port = window.location.port
const isHttps = window.location.protocol.includes('https')
if (isHttps) {
// https协议 对应的wss + 链接地址
socketUrl = `wss://${host}/`
} else {
// http协议 对应的ws
socketUrl = `ws://${host}/`
}
// 创建一个
v.socket = new WebSocket(socketUrl)
// 监听socket打开
v.socket.onopen = function () {
console.log('与服务器建立链接')
// 发送心跳 ping 页面会一直向服务器发送 ping 来保持连接不自动断开
heartTime = setInterval(()=>{
ws.socket.send(JSON.stringify({method: 'ping'}))
},10000)
}
// 接收服务端发来的消息
v.socket.onmessage = async function (msg) {
// msg 服务端返回的消息
}
// 监听socket错误
v.socket.onerror = function (e) {
console.log('WebSocket错误', e)
}
// 监听socket关闭
v.socket.onclose = function (e) {
// 清除心跳定时器
if(heartTime){
clearInterval(heartTime);
}
if(e.code == 1000){
// 正常关闭
}else{
if (this.$route.path === '/') {
// 重新链接
setTimeout(() => {
webSocket(v)
}, 2000)
}
}
console.log('WebSocket已关闭', e)
}
}
}
<template>
</template>
<script>
import { webSocket } from 'webSocket.js'
export default {
created(){
// 创建连接
webSocket(this);
},
beforeDestroy(){
// 主动关闭连接
this.socket.close();
}
}
</script>
<style>
</style>