Skip to content

Instantly share code, notes, and snippets.

@kzaremski
Created May 9, 2021 21:52
Show Gist options
  • Save kzaremski/9298460289b7807cd335159f22906881 to your computer and use it in GitHub Desktop.
Save kzaremski/9298460289b7807cd335159f22906881 to your computer and use it in GitHub Desktop.
WebSocket Client w/ Callbacks for Requests
/*
Websocket w/ Callback
Konstantin Zaremski
*/
class WScallback {
constructor() {
this.running = {};
}
connect(addr, callback) {
this.socket = new WebSocket(addr);
this.socket.onopen = function() {
if (callback) {
callback();
}
}
this.socket.onmessage = (e) => {
var response = JSON.parse(e.data);
this.running[response.id](response.data, response.error);
delete this.running[response.id];
}
}
request(request, callback) {
if (this.socket.readyState == 1) {
var newID = performance.now().toString();
this.running[newID] = callback;
this.socket.send(JSON.stringify({
request:request,
id:newID
}));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment