Skip to content

Instantly share code, notes, and snippets.

@msackman
Created December 18, 2016 21:38
Show Gist options
  • Save msackman/69d843d93bcfb3332f19703357cf022e to your computer and use it in GitHub Desktop.
Save msackman/69d843d93bcfb3332f19703357cf022e to your computer and use it in GitHub Desktop.
example doing the very initial handshake with new websocket support
<!DOCTYPE html>
<meta charset="utf-8" />
<title>WebSocket Test</title>
<script src="https://rawgit.com/kawanet/msgpack-lite/master/dist/msgpack.min.js"></script>
<script language="javascript" type="text/javascript">
var wsUri = "wss://localhost:9999/ws";
var output;
var websocket;
var state = function () {
doSend(msgpack.encode({Product: "GoshawkDB", Version: "dev"}));
state = function() {}
};
function init()
{
output = document.getElementById("output");
testWebSocket();
}
function testWebSocket()
{
websocket = new WebSocket(wsUri);
websocket.binaryType = 'arraybuffer';
websocket.onopen = function(evt) { onOpen(evt) };
websocket.onclose = function(evt) { onClose(evt) };
websocket.onmessage = function(evt) { onMessage(evt) };
websocket.onerror = function(evt) { onError(evt) };
}
function onOpen(evt)
{
writeToScreen("CONNECTED");
state();
}
function onClose(evt)
{
writeToScreen("DISCONNECTED");
}
function onMessage(evt)
{
var payload = msgpack.decode(new Uint8Array(evt.data));
console.log(payload);
writeToScreen('<span style="color: blue;">RESPONSE: ' + JSON.stringify(payload) +'</span>');
}
function onError(evt)
{
console.log(evt)
writeToScreen('<span style="color: red;">ERROR:</span> ' + JSON.stringify(evt));
}
function doSend(message)
{
writeToScreen("SENT: " + JSON.stringify(message) + ":" + websocket.send(message));
}
function writeToScreen(message)
{
var pre = document.createElement("p");
pre.style.wordWrap = "break-word";
pre.innerHTML = message;
output.appendChild(pre);
}
window.addEventListener("load", init, false);
</script>
<h2>WebSocket Test</h2>
<div id="output"></div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment