React-Native-Reconnecting-WebSocket
React native auto reconnect websocket extends WebSocketModule. API design referenced reconnecting-websocket.
🇨🇳中文文档
It is API compatible, so when you have:
var ws = 'ws://....';
you can replace with:
var ws = 'ws://....';
Less code, more exponential.
Install
npm i react-native-reconnecting-websocket
Parameters
var socket = url protocols options;
url
- The URL you are connecting to.
- https://html.spec.whatwg.org/multipage/comms.html#network
protocols
- Optional string or array of protocols per the WebSocket spec.
- https://tools.ietf.org/html/rfc6455
options
- Options (see below)
Options
Options can either be passed as the 3rd parameter upon instantiation or set directly on the object after instantiation:
var socket = url null reconnectInterval: 3000;
reconnectInterval
- The number of milliseconds to delay before attempting to reconnect.
- Accepts
integer
- Default:
1000
maxReconnectInterval
- The maximum number of milliseconds to delay a reconnection attempt.
- Accepts
integer
- Default:
30000
reconnectDecay
- The rate of increase of the reconnect delay. Allows reconnect attempts to back off when problems persist.
- Accepts
integer
orfloat
- Default:
1.5
timeoutInterval
- The maximum time in milliseconds to wait for a connection to succeed before closing and retrying.
- Accepts
integer
- Default:
2000
maxReconnectAttempts
- 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
integer
ornull
. - Default:
null
Methods
See the detail in react-native/WebSocket.js
How to add heartbeat?
- usual
ws = "ws://..."; ws { console};ws { console};ws { console};ws { console}; // add listen connecting event// @params reconnectAttempts 尝试重连的次数ws { console}
- add heartbeat
ws { // execute immediately! ws; heartCheckstart}; ws { heartCheckstart}; var heartCheck = timeout: 10000//default 10s timeoutObj: null serverTimeoutObj: null { ; ; return this; } { let self = this; thistimeoutObj = }
- 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