Skip to content

Instantly share code, notes, and snippets.

@sysnajar
Last active November 27, 2015 11:58
Show Gist options
  • Select an option

  • Save sysnajar/9efad678a5db86c39cb9 to your computer and use it in GitHub Desktop.

Select an option

Save sysnajar/9efad678a5db86c39cb9 to your computer and use it in GitHub Desktop.
HTML5 client do pub/sub via Websocket
HTML5 client do pub/sub via Websocket
ws.send('SUBSCRIBE', 'x');
<html>
<head>
<script>
var ws = null;
function connect() {
if (ws !== null) return log('already connected');
ws = new WebSocket('ws://xxxxxxx:99999/');
ws.onopen = function () {
log('connected to web socket');
};
ws.onerror = function (error) {
log(error);
};
ws.onmessage = function (e) {
log('recv: ' + e.data);
};
ws.onclose = function () {
log('disconnected');
ws = null;
};
return false;
}
function disconnect() {
if (ws === null) return log('already disconnected');
ws.close();
return false;
}
function send() {
if (ws === null) return log('please connect first');
var text = document.getElementById('text').value;
document.getElementById('text').value = "";
log('send: ' + text);
ws.send(text);
return false;
}
function log(text) {
var li = document.createElement('li');
li.appendChild(document.createTextNode(text));
document.getElementById('log').appendChild(li);
return false;
}
</script>
</head>
<body>
<form onsubmit="return send();">
<button type="button" onclick="return connect();">
Connect
</button>
<button type="button" onclick="return disconnect();">
Disconnect
</button>
<input id="text" type="text">
<button type="submit">Send</button>
</form>
<ol id="log"></ol>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment