Connecting to the Jet bus and add a state
A Pen by Gerhard Preuss on CodePen.
| <h1>Jet Peer Add State Demo</h1> | |
| <form class="pure-form"> | |
| <fieldset> | |
| <legend>Jet Configuration</legend> | |
| <label for="url">Daemon URL:<input type="text" value="ws://jet.nodejitsu.com" id="url"></input></label> | |
| <button class="pure-button pure-button-primary">connect</button> | |
| </fieldset> | |
| </form> | |
| <h1>Status: <span id="status"></span></h1> | |
| <p>In case of trouble you may <a href="http://websocketstest.com" target="_blank" class="help">check your Websockets</a> to the outer world.</p> | |
| <div id="log"> | |
| <table class="pure-table"> | |
| <caption>Message Log</caption> | |
| <thead> | |
| <tr> | |
| <td>Time</td> | |
| <td>Direction</td> | |
| <td>Message</td> | |
| </tr> | |
| </thead> | |
| <tbody> | |
| </tbody> | |
| </table> | |
| </div> |
Connecting to the Jet bus and add a state
A Pen by Gerhard Preuss on CodePen.
| var connect = function(url) { | |
| try { | |
| $('#status').text('disconnected'); | |
| // create a Jet Peer, providing the Jet (Daemon) Websocket URL | |
| var peer = new jet.Peer({ | |
| url: url, | |
| onOpen: function() { | |
| $('#status').text('connected'); | |
| }, | |
| onSend: function(message) { | |
| addLogEntry('Out',message); | |
| }, | |
| onReceive: function(message) { | |
| addLogEntry('In',message); | |
| } | |
| }); | |
| var random = 'random' + new Date().getTime(); | |
| // add as notification | |
| peer.state({ | |
| path: random, | |
| value: 123 | |
| }); | |
| random = 'random_2_' + new Date().getTime(); | |
| // add as request | |
| peer.state({ | |
| path: random, | |
| value: 123 | |
| },{ | |
| success: function() { | |
| console.log('ok'); | |
| }, | |
| error: function(err) { | |
| console.log(err); | |
| } | |
| }); | |
| } catch(err) { | |
| $('#status').text('error ' + err); | |
| } | |
| }; | |
| // try to (re-)connect when button is clicked | |
| $('button').click(function(e) { | |
| connect($('input').val()); | |
| }); | |
| // try to (re-)connect when input field changed | |
| $('input').change(function(e) { | |
| connect($('input').val()); | |
| }); | |
| // initially try to reach the jet daemon hosted at nodejitsu.com (which listens on port 80) | |
| connect('ws://jet.nodejitsu.com'); | |
| var off; | |
| var addLogEntry = function(direction, message) { | |
| var now = new Date().getTime(); | |
| if (!off) { | |
| off = now; | |
| } | |
| var tr = $('<tr></tr>'); | |
| tr.append('<td>' + (now-off) + '</td>'); | |
| tr.append('<td>' + direction + '</td>'); | |
| tr.append('<td>' + message + '</td>'); | |
| $('#log tbody').append(tr); | |
| }; |
| .url { | |
| width: 16em; | |
| } |