Websocketification Client
Websocketification Client in the fetch
way with the help of WebpackJs
.
TODO
- [ ] Add Tests.
- [ ] Update Docs.
- [ ] Connection Retry.
- [ ] Connection retry max time.
- [x] Compile es6 to es5.
- [ ] Separate project.
Installation
npm install --save websocketification-client
Browser-Side Usage
Integrate websocketification-client
in the following way and pack it with WebpackJs
before execute it in the browser.
const WebsocketificationClient = require('websocketification-client');
const client = new WebsocketificationClient('ws://127.0.0.1:3123/');
client.connect();
const fetch = client.fetch;
let options = {
method: 'POST',
credentials: 'include',
headers: {'Content-Type': 'application/json'},
body: {name: 'Tom'}
};
return fetch('/users', options).then(
response => response.json()
).then(response => {
console.log('Got users: ', response);
}).catch(error => {
console.error('Failed to get users: ', error);
});
/**
* Add on broadcast listener.
*/
client.setOnBroadcastListener('app.messages', (error, message) => {
if (error) {return console.error(error);}
console.log(message);
});
Server/NodeJs Side Usage
To run in the server, use ws
as the global.WebSocket
Object.
@see ./examples/get-started.js
.
if ('undefined' === typeof(window) && !global.WebSocket) {
global.WebSocket = require('ws');
}
// ...
First
- CONNECTING
- Wait for connection.
- OPEN
- Send Request
- CLOSING
- CLOSED
- If first time return error.
- If not first time reconnect immediately.
Heartbeat Package Policy
- Send heartbeat every 50 seconds.
- Heartbeat will be
@${beat-times}
string.
Connection Retry and Reconnection Policy
When the connection between the client and server breaks, the client will:
- try to reconnect after 5 seconds.
- reconnect immediately if any request is about to send.
- wait for 10 seconds and reconnect, if last step failed.
- wait for 20 seconds and reconnect, if last step failed.
- wait for 40 seconds and reconnect, if last step failed.
- wait for 80 seconds and reconnect, if last step failed.
Disconnect Timer
Reasons WebSocket Connection Breaks
- Client disconnects.
- Connection times out.
- Client physically disconnects, no Internet, weak signal.
- Server goes down temporarily.
- Server goes down permanently.
References
- WebSocket Protocol: https://tools.ietf.org/html/rfc6455
- WebScoket API: https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API
- Close Event: https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent