socket.js
let Socket = ''
let setIntervalWesocketPush = null
/**
* 定义参数。
* 根据实际情况来定义
*/
let number = ""
let accId = ""
let sourId = ""
import baseURL from '@/utils/env' // 这个是自己项目设置的接口地址
/**建立连接 */
export function createSocket(serviceNumber) {
number = serviceNumber
const WSS_URL = `${baseURL.websocket}/${number}` // websocket 连接地址带参数
Socket = new WebSocket(WSS_URL)
Socket.onopen = onopenWS
Socket.onmessage = onmessageWS
Socket.onerror = onerrorWS
Socket.onclose = oncloseWS
}
/**打开WS之后发送心跳 */
export function onopenWS() {
sendPing() //发送心跳
}
/**连接失败重连/关闭 */
export function onerrorWS() {
clearInterval(setIntervalWesocketPush)
// Socket.close()
createSocket(number) //重连
}
/**WS数据接收统一处理 */
export function onmessageWS(e) {
window.dispatchEvent(new CustomEvent('onmessageWS', {
detail: {
data: JSON.parse(e.data)
}
}))
}
/**发送数据
* @param eventType
*/
export function sendWSPush(eventTypeArr) {
const obj = {
appId: 'airShip',
cover: 0,
event: eventTypeArr
}
if (Socket !== null && Socket.readyState === 3) {
Socket.close()
createSocket() //重连
} else if (Socket.readyState === 1) {
Socket.send(JSON.stringify(obj))
} else if (Socket.readyState === 0) {
setTimeout(() => {
Socket.send(JSON.stringify(obj))
}, 3000)
}
}
/**关闭WS */
export function oncloseWS() {
clearInterval(setIntervalWesocketPush)
Socket.close()
}
/**发送心跳 */
export function sendPing() {
Socket.send('ping')
setIntervalWesocketPush = setInterval(() => {
Socket.send('ping')
}, 5000)
}
vue中使用
// 引用socket.js
import {createSocket,oncloseWS} from './socket'
// 创建链接
createSocket(this.serviceNumber)
// 监听消息返回
window.addEventListener('onmessageWS', this.onmessageWS)
//websocket消息处理
onmessageWS(e){
//流程跑完关闭websocket
oncloseWS()
}