Share
Embed
Transcript
55 slides
-
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 -
Who are you ? Developers ? System engineers ? Experience
with websockets ? -
OLD : Show content, wait for user to click link
or button vs NEW : Show content + send user real-time updates -
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 -
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 -
Long polling Client Server GET /updates GET /updates 3 2
1 4 Time {status:’1’, ...} New data arrives -
WebSockets Client Server Initiate and upgrade connection 3 2 1
4 Time New data arrives New data arrives New data arrives New data arrives -
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 -
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) -
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 -
WebSockets – Events & Methods Events Open Close Message Error
Methods send() close() -
Uses Synchronization of data between users Multiplayer HTML5 games Live
feeds Auctions Real-time updates on running processes Financial applications Messaging / chat -
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 -
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 -
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 -
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(); -
Sending information ws.send('Some data in a string'); ws.send(JSON.stringify({'data': 'value here'}));
ws.send(new Blob(['abc123'], {type: 'text/plain'})); -
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(); -
Using PubSub Publish/Subscribe Central message broker Clients publish messages or
subscribe Examples : MQTT (Mosquitto) Redis -
Pubsub example : stock price MQTT StockPrice External source Publish
to StockPrice AMZN : 940 AMZN : 940 -
Pubsub example : stock price MQTT StockPrice External source AMZN
: 940 AMZN : 940 -
Remote Procedure Calls (RPC) Connect to Websocket Make a call
Wait for the result Possibly do something with the result -
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 ... -
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 -
Aggregator Device status Aggregator process Websocket server Device B process
Device A process Network Serial updateStatus ( devicename, status ) RPC : -
Aggregator Websocket server RPC : updateStatus(“A”, 1) Pub : {
“status”: “OK” } Device B process Device A process Network Serial Device status Aggregator process -
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 -
Live control via RPC Websocket server UI RPC : DispenseCoin(qty)
Device C process Serial -
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 -
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 -
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