Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@geethanjalieswaran
Created February 27, 2017 12:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save geethanjalieswaran/dc5a432a4f1e45df253eb1d29d76a73e to your computer and use it in GitHub Desktop.
Save geethanjalieswaran/dc5a432a4f1e45df253eb1d29d76a73e to your computer and use it in GitHub Desktop.
Sample websocket client
<!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