Upgrade to Pro — share decks privately, control downloads, hide ads and more …

websockets-as-the-glue-to-interactivity.pdf

Amanda Goff
October 11, 2023
65

 websockets-as-the-glue-to-interactivity.pdf

Amanda Goff

October 11, 2023
Tweet

Transcript

  1. Who am I ? Wim Godden (@[email protected]) Founder of Cu.be

    Solutions (https://cu.be) Open Source developer since 1997 Creator of PHPCompatibility Speaker at PHP and Open Source conferences
  2. OLD : Show content, wait for user to click link

    or button vs NEW : Show content + send user real-time updates
  3. 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
  4. 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
  5. Long polling Client Server GET /updates GET /updates 3 2

    1 4 Time {status:’1’, ...} New data arrives
  6. WebSockets Client Server Initiate and upgrade connection 3 2 1

    4 Time New data arrives New data arrives New data arrives New data arrives
  7. 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
  8. WebSockets - (sub)protocols Must be supported by client and server

    Several popular ones WAMP (provides PubSub & RPC) STOMP (provides messaging) Can be application specific (custom)
  9. WebSockets – async required ! Asynchronous communication Both client and

    server must do this Can PHP do async ? Since PHP 5.3 through pthreads Since PHP 4.1 through pcntl_fork
  10. Uses Synchronization of data between users Multiplayer HTML5 games Live

    feeds Auctions Real-time updates on running processes Financial applications Messaging / chat
  11. 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
  12. 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
  13. Separate Websocket server or code integrated Separate (for example Crossbar)

    Clients can use PubSub Clients can register RPC → code is executed here Clients can call RPC More infrastructure (but one-time) Easier to separate concerns (domains) Scales well Code integrated (for example PHP based) Clients can only use what the code offers Server registers RPC, so it executes the code Less infrastructure Doesn’t scale well
  14. 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();
  15. Websocket + server-side code in 1 process use Ratchet\MessageComponentInterface; use

    Ratchet\ConnectionInterface; use Ratchet\Server\IoServer; use Ratchet\WebSocket\WsServer; 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();
  16. Remote Procedure Calls (RPC) Connect to Websocket Make a call

    Wait for the result Possibly do something with the result
  17. Use cases for RPC Anything requiring approval or status change

    before continuing Financial transactions Physical change such as opening of a door, turning on/off a light, .. Streaming ...
  18. Single or multiple websocket processes ? Single for : Simple

    apps (like chat) Complex apps with trusted clients only Multiple for : Complex apps with web or other untrusted clients High-traffic Note : Multiple adds complexity if they need to communicate If your websocket server runs code, each process is
  19. Aggregator Device status Aggregator process Websocket server Device B process

    Device A process Network Serial updateStatus ( devicename, status ) RPC :
  20. Aggregator Websocket server RPC : updateStatus(“A”, 1) Pub : {

    “status”: “OK” } Device B process Device A process Network Serial Device status Aggregator process
  21. Aggregator { “devicestatus”: { “A”: { “last-update”: “2022-11-28 00:05:05”, “online”:

    true }, “B”: { “last-update”: “2022-11-28 00:05:08”, “online”: true }, “C”: { “online”: false } } UI Websocket server Device status Aggregator process
  22. Not just hardware of course ;-) Infrastructure monitoring (server status,

    disk usage, …) Aggregation of events Multiple RPC calls Wait for all to complete Reduces total processing time Easier to scale
  23. 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
  24. Useful tools Chrome developer console Thor (benchmark) - https://github.com/observing/thor Websocket-bench

    - https://github.com/M6Web/websocket- bench Socket.io (for backward compatibility) SockJS (for backward compatibility) Crossbar.io Crossbar = Websocket server with WAMP support Autobahn = open source library for talking WAMP voryx/Thruway = PHP library