diff options
author | Kyle Gunger <corechg@gmail.com> | 2020-09-18 12:19:44 -0400 |
---|---|---|
committer | Kyle Gunger <corechg@gmail.com> | 2020-09-18 12:19:44 -0400 |
commit | dbaf69557c0d6e648120b068fec1920b9391a24a (patch) | |
tree | f31f7b956455b1243d344d0c54d5b04e9e80fb3f /scripts/socket | |
parent | e5515d3e1603339b4957421c9494ca619490a03d (diff) |
Update from local repo
Diffstat (limited to 'scripts/socket')
-rw-r--r-- | scripts/socket/message.js | 18 | ||||
-rw-r--r-- | scripts/socket/sock.js | 65 |
2 files changed, 83 insertions, 0 deletions
diff --git a/scripts/socket/message.js b/scripts/socket/message.js new file mode 100644 index 0000000..044027d --- /dev/null +++ b/scripts/socket/message.js @@ -0,0 +1,18 @@ +'use strict'; + +class Message{ + constructor (type, data) + { + this.t = type; + this.d = data; + } + + stringify () + { + var dat = this.d + if(typeof dat !== "string"){ + dat = JSON.stringify(dat); + } + return JSON.stringify({type: this.t, data: dat}); + } +} diff --git a/scripts/socket/sock.js b/scripts/socket/sock.js new file mode 100644 index 0000000..4eacc18 --- /dev/null +++ b/scripts/socket/sock.js @@ -0,0 +1,65 @@ +// A wrapper around the wrapper +class SockWorker extends EventTarget{ + constructor (serveraddr, version) + { + super(); + + this.server = serveraddr; + this.version = version; + } + + // Initialize the connection. + init () { + if(this.server == "" || this.server == null) { + return; + } + try { + this.socket = new WebSocket(this.server); + + this.socket.addEventListener("open", this.o.bind(this)); + this.socket.addEventListener("message", this.msg.bind(this)); + + this.socket.addEventListener("closed", this.c.bind(this)); + this.socket.addEventListener("error", this.err.bind(this)); + } catch (e) { + this.err(); + } + } + + // Called when the connection connects to the server + o () { + this.send("version", this.version); + } + + // Called when the connection gets a message from the server + // Attempts to turn the message into a usable object and pass it to the callback + msg (e) { + if(typeof e.data == "string") { + var dat = JSON.parse(e.data) + this.dispatchEvent(new Event(dat.type, dat.data)); + } + } + + // Called when the connection closes. + // Passes a close object to the callback. + c () { + this.dispatchEvent(new Event("closed")); + } + + // Called when the connection encounters an error. + // Passes an error to the callback + err () { + this.dispatchEvent(new Event("error")); + } + + // Call to close the connection to the server + close () { + this.socket.close(); + } + + // Send a message to the server + send (type, data) { + var m = new Message(type, data); + this.socket.send(m.stringify()) + } +} |