Skip to content

Instantly share code, notes, and snippets.

@dheerajsuthar
Created December 6, 2018 21:24
Show Gist options
  • Save dheerajsuthar/f2d414792b3108cd9ea7144b2e066a55 to your computer and use it in GitHub Desktop.
Save dheerajsuthar/f2d414792b3108cd9ea7144b2e066a55 to your computer and use it in GitHub Desktop.
Simple Subscriber using WebSockets client API
<!DOCTYPE html>
<html>
<head>
<style>
body {
font-family: Tahoma, Geneva, sans-serif;
}
div {
display: inline;
}
</style>
<script>
function subscribe() {
var message = document.getElementById('message');
var channel = document.getElementById('channel').value;
var host = window.document.location.host.replace(/:.*/, '');
var ws = new WebSocket('ws://' + host + ':8080');
ws.onopen = function () {
ws.send(JSON.stringify({
request: 'SUBSCRIBE',
message: '',
channel: channel
}));
ws.onmessage = function(event){
data = JSON.parse(event.data);
message.innerHTML = data.message;
};
};
}
</script>
</head>
<body>
<h1>Subscriber</h1>
<input type="text" id="channel" placeholder="Channel (weather, sports etc.)" />
<button onclick="subscribe()">Subscribe</button>
<div>
<h1>Message:</h1>
<div id="message"></div>
</div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment