Echo server via WebSocket
<!DOCTYPE HTML> <html lang = "en"> <head> <style type = "text/css"> .error {/*from w w w . ja va2 s .c o m*/ color: red; } .response { color: blue; } fieldset { width: 80%; margin: auto; text-align: center; -moz-box-shadow: 10px 10px 10px #000000; -webkit-box-shadow: 10px 10px 10px #000000; } #output { font-family: monospace; width: 80%; margin-left: auto; margin-right: auto; margin-top: 1em; background-color: #eeeeee; padding: 1em; border: 5px groove #cccccc; } </style> <script language="javascript" type="text/javascript"> let output; let websocket; function init(){ output = document.getElementById("output"); } function connect(){ //open socket if ("WebSocket" in window){ websocket = new WebSocket("ws://echo.websocket.org/"); //note this server does nothing but echo what was passed output.innerHTML = "connecting..." ; //attach event handlers websocket.onopen = onOpen; websocket.onclose = onClose; websocket.onmessage = onMessage; websocket.onerror = onError; } else { console.log("WebSockets not supported on your browser."); output.innerHTML = "<p>WebSockets not supported on your browser.</p>"; } } function onOpen(evt){ //called as soon as a connection is opened output.innerHTML = "<p>CONNECTED TO SERVER</p>"; } function onClose(evt){ //called when connection is severed output.innerHTML += "<p>DISCONNECTED</p>"; } function onMessage(evt){ //called on receipt of message output.innerHTML += "<p class = 'response'>RESPONSE: " + evt.data + "</p>"; } function onError(evt){ //called on error output.innerHTML += "<p class = 'error'>ERROR: " + evt.data + "</p>"; } function sendMessage(){ //get message from text field txtMessage = document.getElementById("txtMessage"); message = txtMessage.value; //pass message to server websocket.send(message); output.innerHTML += "<p>MESSAGE SENT: " + message + "</p>"; } </script> </head> <body onload = "init()"> <h1>Web Socket Echo Chamber</h1> <form action = ""> <fieldset> <button type = "button" onclick = "connect()"> connect to server </button> <label for = "txtMessage"> <input type = "text" id = "txtMessage" value = "HTML5 Quick Reference for Dummies" /> </label> <button type = "button" onclick = "sendMessage()"> send message </button> <button type = "button" onclick = "websocket.close()"> disconnect </button> </fieldset> </form> <div id="output">Click 'connect' button to connect</div> </body> </html>