1.创建websocket.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
const WSS_URL = `wss://wss.xxxx.com/ws?appid=xxx`
let Socket = ''
let setIntervalWesocketPush = null

/**建立连接 */
export function createSocket() {
if (!Socket) {
console.log('建立websocket连接')
Socket = new WebSocket(WSS_URL)
Socket.onopen = onopenWS
Socket.onmessage = onmessageWS
Socket.onerror = onerrorWS
Socket.onclose = oncloseWS
} else {
console.log('websocket已连接')
}
}
/**打开WS之后发送心跳 */
export function onopenWS() {
sendPing() //发送心跳
}
/**连接失败重连 */
export function onerrorWS() {
clearInterval(setIntervalWesocketPush)
Socket.close()
createSocket() //重连
}
/**WS数据接收统一处理 */
export function onmessageWS(e) {
window.dispatchEvent(new CustomEvent('onmessageWS', {
detail: {
data: e
}
}))
}
/**发送数据
* @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)
console.log('websocket已断开')
}
/**发送心跳 */
export function sendPing() {
Socket.send('ping')
setIntervalWesocketPush = setInterval(() => {
Socket.send('ping')
}, 5000)
}

2.调用方式

1
2
3
4
5
6
7
8
9
10
11
12
13
import { createSocket, sendWSPush } from './api/websocket'

createSocket() //创建
sendWSPush(11111) //发送数据

//监听ws数据响应
const getDataFunc = function(e) {
console.log(e.detail.data)
}
window.addEventListener('onmessageWS', getDataFunc)

//根据需要,销毁事件监听
window.removeEventListener('onmessageWS', getDataFunc)