Demonstration of a Web Client connected to WebSocket
This file contains 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
<!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://echo.websocket.org/"; | |
var output; | |
var socket; | |
function init() { | |
output = document.getElementById("output"); | |
if (window.WebSocket) { | |
// WebSocket supported | |
writeToScreen("WebSocket supported"); | |
testWebSocket(); | |
} else { | |
// WebSocket not supported | |
writeToScreen("WebSocket not supported"); | |
} | |
} | |
function testWebSocket() { | |
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.data); | |
} | |
function doSend(message) { | |
if (socket.readyState != WebSocket.OPEN) | |
return; | |
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