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

115 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, as well as when not 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. Who am I ? Wim Godden (@wimgtr) Founder of Cu.be Solutions (https://cu.be) Open Source developer since 1997 Developer of PHPCompatibility, OpenX, ... Speaker at PHP and Open Source conferences
  12. 12. Who are you ? Developers ? System engineers ? Experience with websockets ?
  13. 13. Real-time = key to keep users on your platform
  14. 14. 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
  15. 15. The first real-time implementation : AJAX polling Client Server GET /updates {updated:’0’} GET /updates GET /updates {updated:’1’, data:’...’} GET /updates 3 2 1 4 Time {updated:’0’} {updated:’0’} New data arrives
  16. 16. Long polling Client Server GET /updates GET /updates 3 2 1 4 Time {updated:’1’, data:‘...’} New data arrives
  17. 17. 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
  18. 18. Establishing a TCP connection Client Server SYN SYN ACK ACK Data GET /some-url 0 50 100 150
  19. 19. SSL/TLS Client Server 0 50 100 150 200 250 GET /some-url SYN ClientHello SYN ACK ACK ServerHello Certificate ServerHelloDone ClientKeyExchange ChangeCipherSpec Finished ChangecipherSpec Finished DATA 300 350
  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 predefined exist WAMP (provides PubSub and RPC calls) STOMP (provides messaging) Can be application specific (custom)
  23. 23. WebSockets – Events & Methods Events Open Close Message Error Methods send() close()
  24. 24. 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();
  25. 25. Sending information ws.send('Some data in a string'); ws.send(JSON.stringify({'data': 'value here'})); ws.send(new Blob(['abc123'], {type: 'text/plain'}));
  26. 26. Checking if WebSocket support is enabled if (window.WebSocket) { console.log("BROWSER SUPPORTED"); } else { console.log("BROWSER NOT SUPPORTED"); }
  27. 27. 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();
  28. 28. Next step : adding clients
  29. 29. Next step : dealing with data
  30. 30. Uses Synchronization of data between users Multiplayer HTML5 games Live feeds Auctions Real-time updates on running processes Financial applications Messaging / chat Collaborative editing (Google Docs/Sheets, Confluence, …)
  31. 31. 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
  32. 32. Using PubSub Central message broker Examples : ZeroMQ Redis Crossbar (my favourite !) Publish/Subscribe Clients publish messages or subscribe
  33. 33. Database Using PubSub Crossbar NewsMessages Orders Subscribe news Publish m essages Subscribe orders Publish + subscribe messages Background PHP process
  34. 34. PubSub in Thruway
  35. 35. PubSub in Thruway
  36. 36. RPC (Remote Procedure Call) Crossbar Background PHP process Call pay_creditcard(params) Register RPC pay_creditcard(params) Call pay_creditcard(params) Payment provider
  37. 37. RPC (Remote Procedure Call) Crossbar Background PHP process Call pay_creditcard(params) Register RPC pay_creditcard(params) Call pay_creditcard(params) Payment provider
  38. 38. RPC (Remote Procedure Call) Clients connect to Crossbar 1 registers a procedure on Crossbar All other clients can call this procedure
  39. 39. PHP Websocket server libraries Thruway (PHP version of Autobahn) Ratchet Woketo (client + server, PHP7 only)
  40. 40. Useful tools Chrome developer console Firefox add-on : WebSockets Monitor Interesting read : https://hpbn.co/websocket/
  41. 41. Questions ?
  42. 42. Questions ?
  43. 43. Contact Twitter @wimgtr Slides http://www.slideshare.net/wimg E-mail wim@cu.be Thanks !

×