Skip to content

Instantly share code, notes, and snippets.

@akirattii
Created August 10, 2018 07:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save akirattii/5a37cd116ee3a4c071cb65618777cc9a to your computer and use it in GitHub Desktop.
Save akirattii/5a37cd116ee3a4c071cb65618777cc9a to your computer and use it in GitHub Desktop.
NodeJS: WebSocket Client (Browser-compatible)
/*
websocket client module (supports either NodeJS and browser)
NOTE:
`browserify` makes this websocket client lib browser-compatible.
# Usage
```
const onmessage = function(e) {
console.log("onmessage:", e);
};
(async() => {
// new instance:
const client = new WsClient({
url: "wss://...",
});
// open:
const e = await client.open(onmessage); // callback also available: `client.open(onmessage, (e) => { // connected! });`
const param = {
"hello": "world"
};
// send:
client.send(param);
})().catch(console.error);
```
*/
const WebSocket = require('websocket').w3cwebsocket; // browser compatible websocket module
module.exports = class WsClient {
constructor({
url,
debug = false,
logger = console,
}) {
const self = this;
if (!WsClient.isValidUrl(url))
throw Error(`invalid url: "${url}"`);
this.url = url;
this.debug = debug;
this.logger = logger;
}
async open(onmessage, cb) {
const self = this;
this.client = new WebSocket(this.url);
this.client.onmessage = onmessage;
if (typeof cb === "function") { //callback
this.client.onopen = function(e) {
return cb && cb(e);
};
} else { // async/await
return new Promise(function(resolve, reject) {
self.client.onopen = function(e) {
resolve(e);
};
self.client.onerror = function(err) {
reject(err);
};
});
}
}
close() {
this.client.close();
}
send(param) {
const self = this;
if (!self.client) {
throw Error("ws client not connected yet.");
}
if (typeof param !== "string") {
param = JSON.stringify(param);
}
this.client.send(param);
}
//**************************************************************
// utility static methods
//**************************************************************
static isValidUrl(v) {
return /^wss?:\/\/.+$/.test(v);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment