websocket封装

Posted 小小李的新征程

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了websocket封装相关的知识,希望对你有一定的参考价值。

 1 class SocketPlugin {
 2   constructor (param) {
 3     this.websocket = null
 4     this.isConnect = false
 5     this.timeoutNum = null
 6     this.isActivelyClose = false
 7     this.param = param
 8   }
 9  
10 
11   connect () {
13     this.websocket = new WebSocket(this.param.url)
14     this.initSocket(this.param)
15   }
16  
17 
18   initSocket (param) {
19     this.isActivelyClose = false
20  
21 
22     this.websocket.onclose = e => {
23       console.log(‘websocket连接关闭~‘ + this.param.url)
24       this.isConnect = false
25       // 如果手动关闭则不进行重连
26       if (!this.isActivelyClose) {
27         this.reconnectSocket(param)
28       }
29     }
30  
31 
32     this.websocket.onerror = e => {
33       console.log(‘websocket发生异常~‘ + this.param.url + e)
34       this.reconnectSocket(param)
35     }
36  
37 
38     this.websocket.onopen = () => {
39       console.log(‘websocket已连接~ ‘ + this.param.url)
40       this.isConnect = true
41       if (param.hasOwnProperty(‘msg‘)) {
42         this.send(param.msg || ‘‘)
43       }
44     }
45  
46 
47     this.websocket.onmessage = e => {
48       param.callback(JSON.parse(e.data))
49     }
50   }
51  
52 
53   reconnectSocket (param) {
54     if (this.isConnect === true) {
55       return false
56     }
57     console.log(‘websocket 重新连接~ ‘)
58     this.isConnect = true
59     this.timeoutNum && clearTimeout(this.timeoutNum)
60     this.timeoutNum = setTimeout(() => {
61       this.connect(param)
62       this.isConnect = false
63     }, 1000)
64   }
65  
66 
67   /**
68    * // websocket连接状态下才能进行send
69    * @param {*} msg
70    * 向服务send的消息
71    */
72   send (msg) {
73     this.websocket.send(JSON.stringify(msg))
74   }
75  
76 
77   close () {
78     this.isActivelyClose = true
79     if (this.websocket) {
80       this.websocket.close()
81     }
82   }
83 }
84  
85 
86 export default SocketPlugin
使用:
 1 let  socketConfig: {
 2         url: ‘/ints/websocket/test‘,
 3         callback: this.getSocketMsg,
 4         msg: {
 5           fanId: ‘01‘
 6         }
 7      }
 8  
 9 let  testSocket = new SocketPlugin(socketConfig)
10 // 初始化
11 testSocket .connect()
12 // 发送消息
13 testSocket .send(socketConfig.msg)
14 // 关闭
15 testSocket .close()

 

以上是关于websocket封装的主要内容,如果未能解决你的问题,请参考以下文章

VSCode自定义代码片段14——Vue的axios网络请求封装

VSCode自定义代码片段14——Vue的axios网络请求封装

安卓websocket 封装基于Java-websocket

回归 | js实用代码片段的封装与总结(持续更新中...)

websocket封装使用心跳检测断线重连

Watson语音到文本 - 无法构造'WebSocket':URL包含片段标识符