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()

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM