Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Building interactivity with websockets

334 views

Published on

The time of static or dynamically generated sites is long gone. Non-stop interaction with users is the new normal. However, polling with Ajax requests is processor intensive and cumbersome. Websockets allow you to interact with users in real-time without increasing system load. We'll go through the basics and see all the different options, illustrated with live examples of how and when to use it.

Published in: Technology
  • Be the first to comment

  • Be the first to like this

Building interactivity with websockets

  1. 1. Wim Godden Cu.be Solutions @wimgtr Building interactivity with WebSockets
  2. 2. Who am I ? Wim Godden (@wimgtr)
  3. 3. Where I'm from
  4. 4. Where I'm from
  5. 5. Where I'm from
  6. 6. Where I'm from
  7. 7. Where I'm from
  8. 8. Where I'm from
  9. 9. My town
  10. 10. My town
  11. 11. Belgium – the traffic
  12. 12. Who am I ? Wim Godden (@wimgtr) Founder of Cu.be Solutions (http://cu.be) Open Source developer since 1997 Developer of PHPCompatibility, OpenX, Nginx SLIC, ... Speaker at PHP and Open Source conferences
  13. 13. Who are you ? Developers ? System engineers ? Experience with websockets ?
  14. 14. OLD : Show content, wait for user to click link or button vs NEW : Show content + send user real-time updates
  15. 15. Real-time = key to keep users on your platform
  16. 16. The original implementation : refresh Client Server GET /some-page Page contents GET /some-page GET /some-page GET /some-page 60 30 0 90 Time Page contents Page contents Page contents
  17. 17. The first real-time implementation : AJAX polling Client Server GET /updates {status:’0’} GET /updates GET /updates {status:’1’, ...} GET /updates 3 2 1 4 Time {status:’0’} {status:’0’} New data arrives
  18. 18. Long polling Client Server GET /updates GET /updates 3 2 1 4 Time {status:’1’, ...} New data arrives
  19. 19. SSE (Server Sent Events) Client Server GET /updates 3 2 1 4 Time {status:’1’, ...} New data arrives {status:’6’, ...} New data arrives {status:’1500’, ...} New data arrives
  20. 20. WebSockets Client Server Initiate and upgrade connection 3 2 1 4 Time New data arrives New data arrives New data arrives New data arrives
  21. 21. WebSockets - Handshake Client Server GET GET /chat-client HTTP/1.1 Host: yourhost.com Upgrade: websocket Connection: upgrade Origin: http://yourhost.com Sec-Websocket-Key: c29tZXRoaW5nIHJhbmRvbQ== Sec-Websocket-Protocol: chat Sec-Websocket-Version: 13 HTTP/1.1 101 Switching Protocols Upgrade: websocket Connection: upgrade Sec-Websocket-Accept: cmFuZG9tIGFnYV0aGluZw== Sec-Websocket-Protocol: chat
  22. 22. WebSockets - (sub)protocols Must be supported by client and server Several exist WAMP (provides PubSub) STOMP (provides messaging) Can be application specific (custom)
  23. 23. WebSockets – Events & Methods Events Open Close Message Error Methods send() close()
  24. 24. WebSockets First draft : 2007 Accepted as RFC6455 : December 2011 Browser support IE 10+ Chrome 16+ Safari 5+ Firefox 11+ Opera 12+ Android browser 4.4+ Opera Mini not yet supported Use socket.io for automatic fallback
  25. 25. Uses Synchronization of data between users Multiplayer HTML5 games Live feeds Auctions Real-time updates on running processes Financial applications Messaging / chat
  26. 26. Advantages Full-duplex messaging 100% asynchronous HTTP overhead only on initial handshake Low latency Low bandwidth Messages can be fragmented Sent partially (when message is not complete yet) Sent in-between other messages
  27. 27. Disadvantages No caching (unlike XHR/HTTP) Some application changes required No message acknowledgment built-in Ping-pong (present in RFC) not in most browsers Write your own Use socket.io
  28. 28. Client code var ws = new WebSocket("ws://www.websockets.org"); ws.onopen = function(e) { console.log("Connection open ..."); }; ws.onmessage = function(e) { console.log( "Received Message: " + e.data); }; ws.onclose = function(e) { console.log("Connection closed."); }; ws.send("Hello WebSockets!"); ws.close();
  29. 29. Sending information ws.send('Some data in a string'); ws.send(JSON.stringify({'data': 'value here'})); ws.send(new Blob(['abc123'], {type: 'text/plain'}));
  30. 30. Checking if WebSocket support is enabled if (window.WebSocket) { console.log("BROWSER SUPPORTED"); } else { console.log("BROWSER NOT SUPPORTED"); }
  31. 31. Server-side Code use RatchetMessageComponentInterface; use RatchetConnectionInterface; use RatchetServerIoServer; use RatchetWebSocketWsServer; class MyWsServer implements MessageComponentInterface { public function onOpen(ConnectionInterface $conn) { $conn->send('Test message'); } public function onMessage(ConnectionInterface $conn, $msg) { // Do something with the message } public function onClose(ConnectionInterface $conn) { } public function onError(ConnectionInterface $conn, Exception $e) { } } $server = IoServer::factory( new HTTPServer( new WsServer( new MyWsServer() ) ), 8090 ); $server->run();
  32. 32. Time for a nice demo ;-)
  33. 33. Security Always use TLS (wss:// instead of ws://) Verify the Origin header Pass along a random token to the handshake request
  34. 34. Some minor tips and tricks If you proxy WebSocket traffic through nginx : HAProxy : Interesting read : https://hpbn.co/websocket/ location /websocket { proxy_pass http://backend; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_read_timeout 3600; proxy_send_timeout 3600; } defaults http timeout connect 30s timeout client 30s timeout server 30s timeout tunnel 1h
  35. 35. Useful tools Chrome developer console Firefox add-on : WebSockets Monitor Thor (benchmark) - https://github.com/observing/thor Websocket-bench - https://github.com/M6Web/websocket- bench Socket.io (for backward compatibility) SockJS (for backward compatibility)
  36. 36. Questions ?
  37. 37. Questions ?
  38. 38. Contact Twitter @wimgtr Slides http://www.slideshare.net/wimg E-mail wim@cu.be Thanks !

×