Incredibly simple and extendable WebSocket wrapper with an HTTP repeat request fallback providing a shared API for sending and receiving data. SocketConnect checks if WebSockets are available to the client, if so they perform as normal, if not it falls back to repeat HTTP requests. You can then compare responses and check for new data.
var SocketConnect = require('socketconnect');
import SocketConnect from 'socketconnect';
var connection = new SocketConnect(websocketURL, httpFallbackURL);
If your websocketURL
works as a HTTP fallback by replacing ws://
with http://
there's no need for the second argument as SocketConnect will perform the replacement. However if that's not the case, the second argument is necessary for the HTTP fallback.
connection.send(data);
connection.handleData = function(e) {
console.log('Data:', e);
};
There are two flags for checking whether your SocketConnect has used websockets or the fallback. Use some logic like below to separate your custom event handling:
if (connection.isWebSocket) {
// Custom WebSocket handling here
} else if (connection.isHTTP) {
// Custom HTTP handling here
}
The below API is split is split into WS/HTTP, make sure you override them within the correct block of the above logic.
You'll want to override the native WebSocket event handlers, you can do this on connection.ws.*event*
, e.g.:
connection.ws.onopen = function() {
console.info('Connected!');
};
The same applies for onerror
, onclose
, however you'll handle onmessage
within the shared API handleData
.
IMPORTANT: You must set connection.canSend = true;
within the onopen
event, this ensures you cannot send messages before the connection is established.
SocketConnect falls back to HTTP repeat requests using XMLHttpRequest
.
The request interval is set to 1000(ms) by default, but you can change that using:
connection.setReqInterval(5000); // 5 Seconds
SocketConnect provides access to all status updates from XMLHttpRequest
. You can add any event handler to them using the below:
// Response code 0
connection.reqNotInit = function() {
console.log('Request not initialised.');
};
Response Code | Meaning | SocketConnect Function |
---|---|---|
0 | Request not initialised | reqNotInit |
1 | Server connection established | connectionEstablished |
2 | Request received | reqReceived |
3 | Processing request | processingReq |
Response code 4 is dealt with within the shared API handleData
.