Created
February 27, 2017 12:57
-
-
Save geethanjalieswaran/dc5a432a4f1e45df253eb1d29d76a73e to your computer and use it in GitHub Desktop.
Sample websocket client
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 lang="en"> | |
<head> | |
<title>WebSocket Client</title> | |
<style> | |
#output { | |
border: solid 1px #000; | |
} | |
</style> | |
</head> | |
<body> | |
<form id="form"> | |
<input type="text" id="message"> | |
<button type="submit">Send</button> | |
</form> | |
<hr> | |
<div id="output"></div> | |
<script> | |
var inputBox = document.getElementById("message"); | |
var output = document.getElementById("output"); | |
var form = document.getElementById("form"); | |
function connect() { | |
try { | |
var host = "ws://*hostname*:8000"; | |
console.log("Host:", host); | |
var s = new WebSocket(host); | |
var afterTimeout = function () { | |
if (s.readyState != 1) { | |
console.log("Unable to connect to server, retrying..."); | |
connect(); | |
} | |
} | |
var connectRetry = setTimeout(afterTimeout, 15000); | |
s.onopen = function (e) { | |
console.log("Socket opened."); | |
}; | |
s.onclose = function (e) { | |
connect(); | |
console.log("Socket closed."); | |
}; | |
s.onmessage = function (e) { | |
console.log("Socket message:", e.data); | |
var p = document.createElement("p"); | |
p.innerHTML = e.data; | |
output.appendChild(p); | |
}; | |
s.onerror = function (e) { | |
console.log("Socket error:", e); | |
}; | |
} catch (ex) { | |
console.log("Socket exception:", ex); | |
} | |
} | |
connect() | |
form.addEventListener("submit", function (e) { | |
e.preventDefault(); | |
s.send(inputBox.value); | |
inputBox.value = ""; | |
}, false) | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment