Last active
January 3, 2019 16:53
-
-
Save bitsmanent/75eefe4f246eba8a7893f651895f1d97 to your computer and use it in GitHub Desktop.
Simple websocket API
This file contains hidden or 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
/* Simple WebSocket API. | |
* Dependencies: none. | |
* | |
* Message fields: | |
* msgid: server replies must match this | |
* data: the actual data | |
* | |
* Interface in a nutshell: | |
* - var sd = sock.open("ws://host:port", open_callback) | |
* - sock.send(sd, data, reply_callback); | |
* - sock.on(sd, event_name, event_callback); | |
* - sock.off(sd, event_name); | |
* - sock.close(sd); | |
* | |
* Basic demo: | |
* sock.open("ws://host:post", (sd) => { | |
* sock.on(sd, "message", (msg) => { | |
* console.log("got message", sd, msg); | |
* }); | |
* sock.send(sd, {foo:"bar"}); | |
* }); | |
* | |
* To understand everything else, start reading the open(). | |
*/ | |
/* | |
sock.open("ws://host:post", (sd) => { | |
console.log("sock.open()", sd); | |
sock.on(sd, "message", (msg) => { | |
console.log("got message", sd, msg); | |
}); | |
}); | |
*/ | |
(() => { | |
"use strict"; | |
var sockets = []; | |
function on(sd, ev, cb) { | |
sockets[sd].evs[ev] = cb; | |
} | |
function off(sd, ev) { | |
delete sockets[sd].evs[ev]; | |
} | |
function onmsg(sd, ev) { | |
var d, cb; | |
d = JSON.parse(ev.data); | |
if(sockets[sd].evs[ev.type]) | |
sockets[sd].evs[ev.type](d); | |
cb = sockets[sd].cbs[d.id]; | |
if(cb) { | |
delete sockets[sd].cbs[d.id]; | |
cb(d); | |
} | |
} | |
function close(sd) { | |
sockets[sd].ws.close(); | |
} | |
function open(uri, cb) { | |
var sd = sockets.length, ws; | |
if(!(uri && cb)) | |
return; | |
ws = new WebSocket(uri); | |
ws.onopen = ((ev) => cb(sd)); | |
ws.onclose = ((ev) => delete sockets[sd]); | |
ws.onerror = ((ev) => console.log("ERROR", ev)); | |
ws.onmessage = ((ev) => onmsg(sd, ev)); | |
sockets[sd] = { | |
ws: ws, | |
msgid: 0, | |
cbs: {}, | |
evs: {} | |
} | |
return sd; | |
} | |
function send(sd, data, cb) { | |
data.msgid = ++sockets[sd].msgid; | |
sockets[sd].cbs[data.msgid] = cb; | |
sockets[sd].ws.send(JSON.stringify(data)); | |
} | |
window.sock = { | |
open: open, | |
send: send, | |
close: close, | |
on: on, | |
off: off | |
} | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment