Created
August 10, 2018 07:24
-
-
Save akirattii/5a37cd116ee3a4c071cb65618777cc9a to your computer and use it in GitHub Desktop.
NodeJS: WebSocket Client (Browser-compatible)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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