Save 37% off PRO during our Black Friday Sale! »

Node, Real-time, HTML5: why wait?

Node, Real-time, HTML5: why wait?

C8b387c489181844b3ffc704fadc0f14?s=128

Remy Sharp

May 03, 2012
Tweet

Transcript

  1. Node. Real Time. HTML5. Why Wait? http://www.flickr.com/photos/botosynthetic/7107597727

  2. The Plan • Context - why is real-time important? •

    What is Node.js? • Real-time client technology • My experience • Live coding live data...!
  3. Why do I care about Node?

  4. I worked in the finance web industry, and real-time prices

    were the golden egg.
  5. Comet was the right solution. http://www.flickr.com/photos/chrs_snll/373710073

  6. http://www.flickr.com/photos/chrs_snll/373710073 Comet is hard. Comet is a hack.

  7. None
  8. http://www.flickr.com/photos/blank22763/4089952578

  9. Demos simple chat using long polling. Code is simple. function

    longPoll (data) { // :: snip :: handle the messages // start the long poll again $.ajax({ cache: false, url: "/recv", data: { since: CONFIG.last_message_time, id: CONFIG.id }, success: function (data) { longPoll(data); } });
  10. More importantly, no infrastructure making it hard.

  11. Usual LAMP stack http://www.flickr.com/photos/barkbud/4342814008

  12. Apache pre-forks itself, concurrent connections are limited to apache forks

  13. Apache fires up and kills php, and there is no

    persistence (out of the box).
  14. Node is event driven.

  15. Traditional model • You greet receptionist at doctors • Who

    asks you to fill out forms and conversation back and forth • As you fill out, others are waiting and queuing behind you. • You're blocking.
  16. Event Driven • You greet receptionist at doctors • Who

    asks you to fill out forms and come back once they're complete • As you're filling them out, the next person is dealt with and so on. • Once you're done, you return the forms and are processed.
  17. Warning: Node doesn't solve world poverty.

  18. Node makes complicated server programming easy for web developers http://www.flickr.com/photos/brooke/25588103

  19. Real-time made...

  20. Long polling - keep Ajax request open.

  21. function longPoll() { // <snip> $.ajax({ url: '/prices', type: 'json',

    success: function (data) { failures = 0; showPrices(data); longPoll(); }, error: longPollFailure }); }
  22. Event Source very similar to long polling, except always open.

  23. var es = new EventSource('/prices'); es.onmessage = function (event) {

    var data = JSON.parse(event.data); showPrices(data); };
  24. EventSource • Events emit from server • Read only stream

    • Simple API • Possible to polyfill (so IE support)
  25. EventSource • Supports connection dropping and resuming with Last-Event-ID •

    Supports bespoke events other than `message` • CORS is coming (x-domain SSE)
  26. var es = new EventSource('/prices'); es.onmessage = function (event) {

    var data = JSON.parse(event.data); showPrices(data); };
  27. Web Sockets Node module: websocket.io https://github.com/LearnBoost/websocket.io

  28. var socket = new WebSocket('ws://somesite'); socket.onmessage = function (event) {

    var data = JSON.parse(event.data); showData(data); });
  29. var socket = new WebSocket('ws://somesite'); socket.onmessage = function (event) {

    var data = JSON.parse(event.data); showData(data); }); // <snip> data = { user: 'rem', data: payload }; socket.send(JSON.stringify(data));
  30. WebSockets • Persistent connection • Tiny chunks of data exchanged

    • Bi-directional & no origin rules
  31. WebSockets • Persistent connection • Tiny chunks of data exchanged

    • Bi-directional & no origin rules
  32. Abstractions: Socket.IO most popular and complete.

  33. Example

  34. jsconsole

  35. http://www.flickr.com/photos/jjeff/6320152982

  36. If only I had a two way communication channel with

    the device...
  37. Sockets? Flash is the polyfill, and Android 2.2 has no

    flash.
  38. Event Source + postMessage + Ajax

  39. your mobile site add <script> iframe origin: jsconsole.com jsconsole server

    jsconsole client postMessage & onmessage EventSource Ajax post EventSource Ajax post
  40. Since jsconsole is a client side app, all I need

    to do is replace the static serving with Node and use connect
  41. server.js

  42. Important part that's missing: res.end() and the response object is

    cached for use later on. app.get('/remote/:id/run', function (req, res) { var id = req.params.id; res.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache' }); res.write('id:0\n\n'); sessions.run[id] = res; });
  43. app.post('/remote/:id/run', function (req, res) { var id = req.params.id, data

    = ''; // send to listening connections if (sessions.run[id]) { eventId++; data = 'data:' + req.body.data + '\nid:' + eventId); sessions.run[id].write(data + '\n\n'); } // close the ajax request res.writeHead(200, { 'Content-Type' : 'text/plain' }); res.end(); });
  44. remote-iframe.js

  45. var sse = new EventSource('/remote/' + id + '/run'), win

    = window.top; sse.onmessage = function (event) { win.postMessage(event.data, origin); };
  46. None
  47. Remote Tilt

  48. Remote Tilt • Create same message tunnel as jsconsole •

    Pipe orientation events from phone directly in to desktop browser • Orientation events now tested on desktop
  49. jsbin.com/3/

  50. Real-time !== chat

  51. None
  52. • Mobile users enter twitter handle, and hit my face

    • A socket establishes their connection and notifies server they're still active • Upon hit, message sent to main screen with their score (which is captured using EventSource) • Upon image capture on server, it's piped down to the connected devices.
  53. Few final thoughts

  54. Queuing systems

  55. Sticky sessions and sockets

  56. Or grab me in the breaks. @rem