Last active
June 22, 2019 20:38
-
-
Save dioptre/eb9b1a4a8a94e2040c49cd92918a18a0 to your computer and use it in GitHub Desktop.
Websocket Client auto-connect/reconnect implementation for React Native
This file contains 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
export default class WebSocketClient { | |
constructor(url) { | |
this.number = 0; // Message number | |
this.autoReconnectInterval = 12*1000; // ms | |
this.url = url; | |
this.open(); | |
} | |
open (url){ | |
console.log("WebSocketClient: Connecting..."); | |
if (url) this.url = url; | |
this.instance = new WebSocket(this.url); | |
console.log(this.instance); | |
this.instance.onopen = ()=>{ | |
this.onopen(); | |
}; | |
this.instance.onmessage = (data,flags)=>{ | |
this.number ++; | |
this.onmessage(data,flags,this.number); | |
}; | |
this.instance.onclose = (e)=>{ | |
switch (e.code){ | |
case 1000: // CLOSE_NORMAL | |
console.log("WebSocket: closed"); | |
break; | |
default: // Abnormal closure | |
this.reconnect(e); | |
break; | |
} | |
this.onclose(e); | |
}; | |
this.instance.onerror = (e)=>{ | |
switch (e.code){ | |
case 'ECONNREFUSED': | |
this.reconnect(e); | |
break; | |
default: | |
this.onerror(e); | |
break; | |
} | |
}; | |
} | |
send (data,option){ | |
try{ | |
this.instance.send(data,option); | |
}catch (e){ | |
console.error(e); | |
} | |
} | |
reconnect (e){ | |
console.log(`WebSocketClient: retry in ${this.autoReconnectInterval}ms`,e); | |
//this.instance.removeAllListeners(); | |
var that = this; | |
setTimeout(function(){ | |
that.open(that.url); | |
},this.autoReconnectInterval); | |
} | |
onopen (e){ console.log("WebSocketClient: open",arguments); } | |
onmessage (data,flags,number){ console.log("WebSocketClient: message",arguments); } | |
onerror (e){ console.log("WebSocketClient: error",arguments); } | |
onclose (e){ console.log("WebSocketClient: closed",arguments); } | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
From https://github.com/websockets/ws/wiki/Websocket-client-implementation-for-auto-reconnect