websocket封装

2021-02-16 13:19

阅读:645

标签:nts   clear   const   reconnect   sock   cal   prope   one   发送   

 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封装

标签:nts   clear   const   reconnect   sock   cal   prope   one   发送   

原文地址:https://www.cnblogs.com/hlweng-0207/p/11912009.html

上一篇:常用的JS表单验证

下一篇:JSON方法


评论


亲,登录后才可以留言!