WebSocket 是 HTML5 开始提供的一种在单个 TCP 连接上进行全双工通讯的协议。
WebSocket 通用代码
整体过程:
- 发起连接
- 发送数据(发送心跳等)
- 接收数据
- 关闭连接
- 断线重连
- 异常处理…
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 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103
| export default class WebSocketHandle {
constructor(url, msgCallback, name = 'default') { this.url = url this.msgCallback = msgCallback this.name = name this.ws = null this.status = null }
connect(data, callback) { this.ws = new WebSocket(this.url) this.ws.onopen = e => { this.status = 'open' if (callback) { callback() }
console.log(`${this.name}连接成功`, e)
this.heartCheck()
if (data !== undefined) { return this.ws.send(data) } } this.ws.onmessage = e => { if (e.data === 'pong') { this.pingPong = 'pong' } return this.msgCallback(e.data) } this.ws.onclose = e => { this.closeHandle(e) } this.onerror = e => { this.closeHandle(e) } }
heartCheck() { this.pingPong = 'ping' this.pingInterval = setInterval(() => { if (this.ws.readyState === 1) { this.ws.send('ping') } }, 10000) this.pongInterval = setInterval(() => { this.pingPong = false if (this.pingPong === 'ping') { this.closeHandle('pingPong没有改变为pong') } console.log('返回pong') this.pingPong = 'ping' }, 20000) }
sendHandle(data) { console.log(`${this.name}发送消息给服务器:`, data) return this.ws.send(data) }
closeHandle(e = 'err') { if (this.status !== 'close') { console.log(`${this.name}断开,重连websocket`, e) if (this.pingInterval !== undefined && this.pongInterval !== undefined) { clearInterval(this.pingInterval) clearInterval(this.pongInterval) } this.connect('') } else { console.log(`${this.name}websocket手动关闭`) } }
closeMyself() { console.log(`关闭${this.name}`) this.status = 'close' return this.ws.close() } }
|