Last active
April 16, 2024 10:45
-
-
Save WiwilZ/e055669a01653fea80bcc48a93e2225d to your computer and use it in GitHub Desktop.
WebSocketClient written in js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class WebSocketClient { | |
| constructor(url) { | |
| this.url = url; | |
| this.socket = null; | |
| this.heartBeatTimeout = 45000; | |
| this.timeoutObj = null; | |
| this.lockReconnect = false; | |
| } | |
| create() { | |
| try { | |
| this.socket = new WebSocket(this.url); | |
| this.init(); | |
| } catch(_) { | |
| this.reconnect(); | |
| } | |
| } | |
| init() { | |
| this.socket.onopen = () => { | |
| console.log('socket连接成功'); | |
| this.onBind(); | |
| this.heartBeat(); | |
| }; | |
| this.socket.onclose = e => { | |
| console.warn(e); | |
| console.warn('连接关闭'); | |
| this.reconnect(); | |
| }; | |
| this.socket.onerror = e => { | |
| console.warn('发生异常'); | |
| console.warn(e); | |
| this.reconnect(); | |
| }; | |
| this.socket.onmessage = e => { | |
| this.onMsg(JSON.parse(e.data)); | |
| }; | |
| } | |
| heartBeat() { | |
| this.timeoutObj && clearTimeout(this.timeoutObj); | |
| this.timeoutObj = setTimeout(() => { | |
| if (this.socket.readyState === 1) { | |
| this.socket.send(JSON.stringify({ requestType: 0 })); | |
| } | |
| this.heartBeat(); | |
| }, this.heartBeatTimeout); | |
| } | |
| reconnect() { | |
| if (this.lockReconnect) { | |
| return; | |
| } | |
| this.lockReconnect = true; | |
| const t = setTimeout(() => { | |
| this.create(); | |
| this.onUpdate(); | |
| this.lockReconnect = false; | |
| clearTimeout(t); | |
| }, 4000); | |
| } | |
| close() { | |
| this.socket.close(); | |
| } | |
| send(type, message) { | |
| if (this.socket.readyState === 1) { | |
| this.socket.send(JSON.stringify({type, message})) | |
| } | |
| } | |
| registerHandle(requestType, param) { | |
| if (this.socket.readyState === 1) { | |
| this.socket.send(JSON.stringify({requestType, param})) | |
| } | |
| } | |
| onBind() { | |
| console.log('onBind'); | |
| } | |
| onMsg(data) { | |
| console.log('onMsg', data); | |
| } | |
| onUpdate() { | |
| console.log('onUpdate'); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment