React native auto reconnect websocket extends WebSocketModule. API design referenced reconnecting-websocket.
🇨🇳中文文档
It is API compatible, so when you have:
var ws = new WebSocket('ws://....');you can replace with:
var ws = new ReconnectingWebSocket('ws://....');Less code, more exponential.
npm i react-native-reconnecting-websocketvar socket = new ReconnectingWebSocket(url, protocols, options);- The URL you are connecting to.
- https://html.spec.whatwg.org/multipage/comms.html#network
- Optional string or array of protocols per the WebSocket spec.
- https://tools.ietf.org/html/rfc6455
- Options (see below)
Options can either be passed as the 3rd parameter upon instantiation or set directly on the object after instantiation:
var socket = new ReconnectingWebSocket(url, null, {reconnectInterval: 3000});- The number of milliseconds to delay before attempting to reconnect.
- Accepts
integer - Default:
1000
- The maximum number of milliseconds to delay a reconnection attempt.
- Accepts
integer - Default:
30000
- The rate of increase of the reconnect delay. Allows reconnect attempts to back off when problems persist.
- Accepts
integerorfloat - Default:
1.5
- The maximum time in milliseconds to wait for a connection to succeed before closing and retrying.
- Accepts
integer - Default:
2000
- The maximum number of reconnection attempts that will be made before giving up. If null, reconnection attempts will be continue to be made forever.
- Accepts
integerornull. - Default:
null
See the detail in react-native/WebSocket.js
- usual
ws = new WebSocket("ws://...");
ws.onopen = (e) => {
console.log("onopen",e)
};
ws.onmessage = (evt) => {
console.log("onmessage",JSON.parse(evt.data))
};
ws.onclose = (e) => {
console.log("onclose",e)
};
ws.onerror = (e) => {
console.log("onerror",e)
};
// add listen connecting event
// @params reconnectAttempts 尝试重连的次数
ws.onconnecting = (reconnectAttempts) => {
console.log("onconnecting", reconnectAttempts)
}- add heartbeat
ws.onopen = (e) => {
// execute immediately!
ws.send("heartbeat string");
heartCheck.reset().start()
};
ws.onmessage = (evt) => {
heartCheck.reset().start()
};
ws.onclose = () => {
if(logout){//如果前端主动关闭(如退出登陆),不做处理
}else {//如果服务器主动关闭,前端也需要重连时使用
heartCheck.reset().start()
}
};
var heartCheck = {
timeout: 10000,//default 10s
timeoutObj: null,
serverTimeoutObj: null,
reset:function(){
clearTimeout(this.timeoutObj);
clearTimeout(this.serverTimeoutObj);
return this;
},
start:function(){
let self = this;
this.timeoutObj = setTimeout(function(){
if(ws.readyState === ws.OPEN){
ws.send("heartbeat string");
}
self.serverTimeoutObj = setTimeout(function(){
ws.reconnect();//本库提供
}, self.timeout)
}, this.timeout)
}
}- add new API
reconnect()
/**
* Additional public API method to refresh the connection if still open (close, re-open).
* For example, if the app suspects bad data / missed heart beats, it can try to refresh.
*/
ws.reconnect()