Simple websocket client

This commit is contained in:
Tony Garnock-Jones 2016-11-21 17:05:43 +13:00
parent a2c63ca007
commit 6b4cb0b271
2 changed files with 94 additions and 0 deletions

View File

@ -0,0 +1,44 @@
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8>
<title>WebSub Client</title>
<script src="client.js"></script>
<style>
th, td { vertical-align: top; }
th { text-align: right; border-right: solid black 1px; padding-right: 1em; }
td { text-align: left; padding-left: 1em; }
</style>
</head>
<body>
<h1>WebSub Client</h1>
<h2>Subscription</h2>
<p>
<label for="topic">Topic:</label>
<input type="text" id="topic" name="topic" value="">
</p>
<h2>Latest Notification</h2>
<table>
<tr>
<th>Canonical Hub URL</th>
<td id="canonical-hub"></td>
</tr>
<tr>
<th>Canonical Topic URL</th>
<td id="canonical-topic"></td>
</tr>
<tr>
<th>Content-Type</th>
<td id="content-type"></td>
</tr>
<tr>
<th>Timestamp</th>
<td id="timestamp"></td>
</tr>
<tr>
<th>Content</th>
<td id="content"></td>
</tr>
</table>
</body>
</html>

50
racketmq/htdocs/client.js Normal file
View File

@ -0,0 +1,50 @@
var sock;
window.addEventListener('load', function () {
function reconnect() {
if (sock) {
var oldsock = sock;
sock = null;
oldsock.close();
}
var topic = document.getElementById('topic').value.trim();
if (topic) {
var loc = new URL(document.location);
loc.protocol = (document.location.protocol === 'https:' ? 'wss:' : 'ws:');
loc.pathname = '/hub';
loc.search = 'hub.topic=' + encodeURIComponent(topic) + '&hub.poll_interval_seconds=10';
sock = new WebSocket(loc);
sock.onopen = function (e) {
console.log('sock onopen', e);
};
sock.onmessage = function (e) {
var msg = JSON.parse(e.data);
console.log('sock onmessage', msg);
document.getElementById('canonical-hub').innerText = msg.link.hub;
document.getElementById('canonical-topic').innerText = msg.link.self;
document.getElementById('content-type').innerText = msg['content-type'] ||
'Unknown (assuming "text/plain", trying utf-8 first, falling back to latin-1)';
document.getElementById('timestamp').innerText = new Date();
var content_latin1 = atob(msg['content-base64']);
try {
document.getElementById('content').innerText = decodeURIComponent(escape(content_latin1));
} catch (exn) {
document.getElementById('content').innerText = content_latin1;
}
};
sock.onclose = function (e) {
if (sock !== null) {
console.log('sock onclose', e);
setTimeout(reconnect, 5000);
}
};
}
}
document.getElementById('topic').onchange = reconnect;
reconnect();
});