Created
May 9, 2021 21:52
-
-
Save kzaremski/9298460289b7807cd335159f22906881 to your computer and use it in GitHub Desktop.
WebSocket Client w/ Callbacks for Requests
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 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