Created
December 16, 2015 08:13
-
-
Save davidsm/9976ab72c17f08c20982 to your computer and use it in GitHub Desktop.
Simple wrapper for a Websocket connection that accepts and sends JSON data
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
exports.websocket = { | |
connect: function (address) { | |
var ws = new WebSocket(address); | |
var promise = new Promise(function (resolve, reject) { | |
ws.onopen = function (e) { | |
var wsObj = { | |
socket: ws, | |
handlers: {} | |
}; | |
document.addEventListener("unload", function () { | |
exports.websocket.close(ws); | |
}); | |
ws.onmessage = function (msg) { | |
var parsedMsg; | |
try { | |
parsedMsg = JSON.parse(msg.data); | |
} | |
catch (e) { | |
console.log("Bad WS message"); | |
} | |
var handler = wsObj.handlers[parsedMsg.type]; | |
if (handler) { | |
handler(parsedMsg); | |
} | |
else { | |
console.log("No handler for message type " + parsedMsg.type); | |
} | |
}; | |
resolve(wsObj); | |
}; | |
ws.onerror = function (e) { | |
reject(e); | |
}; | |
}); | |
return promise; | |
}, | |
on: function (ws, type, handler) { | |
ws.handlers[type] = handler; | |
}, | |
send: function (ws, msg) { | |
ws.socket.send(JSON.stringify(msg)); | |
}, | |
close: function (ws) { | |
ws.socket.close(); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment