Skip to content

Instantly share code, notes, and snippets.

@jamchamb
Last active August 20, 2021 03:23
Show Gist options
  • Save jamchamb/ad4dc5d7e6ec061ec2c3fe824efd82cd to your computer and use it in GitHub Desktop.
Save jamchamb/ad4dc5d7e6ec061ec2c3fe824efd82cd to your computer and use it in GitHub Desktop.
Basic interactive WebSocket page based on websocket.org echo test
<!doctype HTML>
<html>
<head>
<meta charset="utf-8" />
<title>WebSocket Test</title>
</head>
<body>
<script language="javascript" type="text/javascript">
//var wsUri = 'ws://demos.kaazing.com/echo';
var output;
function init()
{
output = document.getElementById("output");
testWebSocket();
}
function testWebSocket(wsUri)
{
websocket = new WebSocket(wsUri);
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");
//doSend("hello");
}
function onClose(evt)
{
writeToScreen("DISCONNECTED: " + evt.code);
writeToScreen(evt.reason);
}
function onMessage(evt)
{
writeToScreen('RESPONSE: ' + evt.data, 'blue');
//websocket.close();
}
function onError(evt)
{
writeToScreen('ERROR: ' + evt.data, 'red');
}
function doSend(message)
{
writeToScreen("SENT: " + message);
websocket.send(message);
}
function writeToScreen(message, color='black')
{
var pre = document.createElement("p");
pre.style.wordWrap = "break-word";
pre.style.color = color;
pre.innerText = message;
output.appendChild(pre);
}
window.addEventListener("load", init, false);
</script>
<h2>WebSocket Test</h2>
<form>
<input type="text" id="wsUri" value="ws://demos.kaazing.com/echo" size="70">
<input type="button" id="connectButton" value="Connect" onClick="testWebSocket(getElementById('wsUri').value)">
<input type="button" id="disconnectButton" value="Disconnect" onClick="websocket.close()">
<br>
<textarea id="sendtext">hello world</textarea>
<input type="button" id="sendbutton" value="Send" onClick="doSend(getElementById('sendtext').value)">
</form>
<div id="output"></div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment