Update the websockets code to allow any topic to be subscribed to

This also will prune the messages displayed on the screen at a healthy 25
This commit is contained in:
R. Tyler Croy 2014-11-23 21:53:36 -08:00
parent 97583ccf8f
commit 67af6f81ff
3 changed files with 19 additions and 11 deletions

View File

@ -8,4 +8,7 @@
</div>
<script src="/js/ws.js?1"></script>
<script type="text/javascript">
watchTopic("{{name}}");
</script>
{{> footer}}

View File

@ -1,21 +1,28 @@
if (!window.WebSocket) {
alert("This won't work in your browser. Try Chrome or a gooder version of Safari.");
} else {
function connectWs() {
function watchTopic(name) {
if (!window.WebSocket) {
alert("This won't work in your browser. Try Chrome or a gooder version of Safari.");
}
else {
if (!window.ws || window.ws.readyState != WebSocket.OPEN) {
window.ws = new WebSocket("ws://"+location.host+"/topics/topic/websocket");
window.ws = new WebSocket("ws://" + location.host + "/topics/" + name + "/websocket");
window.ws.onopen = function(event) {
console.log("WebSocket opened!");
};
window.ws.onmessage = function(event) {
console.log(event);
$('#messages').prepend("<div class='list-group-item'>" + event.data + "</div>");
var messages = $('#messages')
messages.prepend("<div class='list-group-item'>" + event.data + "</div>");
// Let's only keep the last 25
if (messages.children().size() > 25) {
messages.children().last().remove();
}
};
window.ws.onclose = function(event) {
var timer = setTimeout(function() {
console.log("Retrying connection...");
connectWs();
watchTopic(name);
if (window.ws.readyState == WebSocket.OPEN) {
clearTimeout(timer);
}
@ -23,6 +30,4 @@ if (!window.WebSocket) {
};
}
}
connectWs();
}

View File

@ -51,11 +51,11 @@ ratpack {
websocket(ctx) { ws ->
println "Connected ${ws} ${subscriber}"
subscriber.callback = { msg ->
println "calledback ${msg}"
println "called back with: ${msg}"
ws.send(msg)
println "sent message"
}
runner.start()
println "lalala"
} connect { sock ->
sock.onClose {
println "closing up ${subscriber}"