Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@dioptre
Last active June 22, 2019 20:38
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dioptre/eb9b1a4a8a94e2040c49cd92918a18a0 to your computer and use it in GitHub Desktop.
Save dioptre/eb9b1a4a8a94e2040c49cd92918a18a0 to your computer and use it in GitHub Desktop.
Websocket Client auto-connect/reconnect implementation for React Native
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