Skip to content

Instantly share code, notes, and snippets.

@devdays
Created November 30, 2014 19:15
Show Gist options
  • Save devdays/10acf34b07fdf75da71b to your computer and use it in GitHub Desktop.
Save devdays/10acf34b07fdf75da71b to your computer and use it in GitHub Desktop.
Web Socket client
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>WebSocket Test</title>
<script type="text/javascript">
var wsUri = 'ws://' + window.location.hostname +
window.location.pathname.replace('index.html', 'ws.ashx');
var output;
var socket;
function init() {
output = document.getElementById("output");
if (window.WebSocket) {
// WebSocket supported
writeToScreen("WebSocket supported");
testWebSocket();
}
}
function testWebSocket() {
writeToScreen("CONNECTING TO " + wsUri);
socket = new WebSocket(wsUri);
socket.onopen = function (evt) { onOpen(evt) };
socket.onclose = function (evt) { onClose(evt) };
socket.onmessage = function (evt) { onMessage(evt) };
socket.onerror = function (evt) { onError(evt) };
}
function onOpen(evt) {
writeToScreen("CONNECTED");
doSend("WebSocket is on the air");
}
function onClose(evt) {
writeToScreen("DISCONNECTED");
}
function onMessage(evt) {
writeToScreen('<span style="color: blue;">RESPONSE: ' +
evt.data.toString() + '</span>');
socket.close();
}
function onError(evt) {
writeToScreen('<span style="color: red;">ERROR:</span> ' +
evt + " at " + evt.currentTarget.url);
}
function doSend(message) {
if (socket.readyState != WebSocket.OPEN)
return;
//if (socket.bufferedAmount < someBufferThresholdinBytes) {
// socket.send(message);
//}
socket.send(message);
writeToScreen("SENT: " + message);
}
function writeToScreen(message) {
var pre = document.createElement("p");
pre.style.wordWrap = "break-word";
pre.innerHTML = message;
output.appendChild(pre);
}
// should probably use jQuery.ready here
if (window.addEventListener) {
// for W3C DOM
window.addEventListener("load", init, false);
} else {
// legacy IE
window.attachEvent("onload", init);
}
</script>
</head>
<body>
<h2>WebSocket Test</h2>
<div id="output"></div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment