The setup
I am using the websockets/ws library to listen to a WSS feed. It works well, it's lightweight enough and it seems to be one of the fastest around (which is important).
I'm trying to differentiate between me programmatically closing the connection, and them closing it for whatever reason.
According to the docs, I can send a code
(int) and a reason
(string), both of which are sent to the on close event. But by all accounts, this functionality no longer exists.
Tests
- Most codes throw a
First argument must be a valid error code number
error - Leaving it blank sends
code = 1005
and an emptyreason
to the event - If I enter a code of
1005
, I get the invalid error - If I enter a code of
1000
, the event receivescode = 1006
and still an emptyreason
(regardless of what I put)
^ tests are simple enough...
var WebSocket = require('ws');
var ws = new WebSocket(url);
ws.on('close', function(code, reason) {
console.log(code);
console.log(reason);
});
var code = 1234,
reason = 'whatever reason';
setTimeout(function() {
ws.close(code, reason);
}, 5000);
But...
I need to be able to tell if I've closed the connection, or if it was closed for another reason (connection lost, they closed it because of time limits, etc). Depending on the reason it was closed, I sometimes need to immediately reopen the connection, but only sometimes.
I can do something like...
_initWS(url) {
var ws = new WebSocket(url);
ws.on('open', function() {...});
ws.on('close', function(code, reason) {
ws = null; // Don't know if needed
ws = _initWS(url); // Reopen the connection, for ever and ever...
});
ws.on('message', funciton(msg) {...});
return ws;
}
var someFeed = _initWS(someURL);
... but since the code
and reason
are all but meaningless, this automatically restarts the connection regardless of why it was closed. This is great if the connection was lost or timed-out, but not so great if I want to close it programmatically...
someFeed.close(); // Connection immediately reopens, always and forever
Question(s)
How can I differentiate between different closes? I don't want to change the library code, because then I can't use npm install
when I move my own code around. Can I override the close method within my own code?
Or is there an equally lightweight and lightning-fast library that has the functionality I'm looking for? I just need to be able to reliably send a unique code
and/or reason
, so I know when I'm trying to close it manually. I know that asking for recommendations is taboo, but there are too many libraries to test each one, and no benchmarks that I can find.