Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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