SlideShare a Scribd company logo
Wim Godden
Cu.be Solutions
@wimgtr
Building interactivity with WebSockets
Who am I ?
Wim Godden (@wimgtr)
Where I'm from
Where I'm from
Where I'm from
Where I'm from
Where I'm from
Where I'm from
My town
My town
Belgium – the traffic
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
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
Real-time = key to keep users on your platform
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
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
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 exist
WAMP (provides PubSub)
STOMP (provides messaging)
Can be application specific (custom)
WebSockets – Events & Methods
Events
Open
Close
Message
Error
Methods
send()
close()
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
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
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'}));
Checking if WebSocket support is enabled
if (window.WebSocket) {
console.log("BROWSER SUPPORTED");
} else {
console.log("BROWSER NOT SUPPORTED");
}
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();
Time for a nice demo ;-)
Security
Always use TLS (wss:// instead of ws://)
Verify the Origin header
Pass along a random token to the handshake request
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
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)
Questions ?
Questions ?
Contact
Twitter @wimgtr
Slides http://www.slideshare.net/wimg
E-mail wim@cu.be
Thanks !

More Related Content

ODP
Your app lives on the network - networking for web developers
PPT
Easy Steps to implement UDP Server and Client Sockets
PPT
Socket programming
PDF
Ethernet Shield
PDF
Socket programming using java
PPT
Tcp sockets
PPT
Networking & Socket Programming In Java
PPT
Basic socket programming
Your app lives on the network - networking for web developers
Easy Steps to implement UDP Server and Client Sockets
Socket programming
Ethernet Shield
Socket programming using java
Tcp sockets
Networking & Socket Programming In Java
Basic socket programming

What's hot (20)

PPTX
Socket programming
PDF
Socket Programming
PPT
Socket programming-tutorial-sk
PPT
Java Socket Programming
PDF
HTTPS: All you need to know
PDF
Arduino práctico ethernet
PDF
Java sockets
PPTX
Elementary TCP Sockets
PPT
Socket programming in C
PDF
Programming TCP/IP with Sockets
PPTX
Socket Programming
PPT
Application Layer and Socket Programming
PPT
Ppt of socket
PDF
Network Sockets
DOC
socket programming
PDF
Lecture10
PPTX
Network programming using python
PPTX
Socket programming in c
PPT
Socket Programming Tutorial
Socket programming
Socket Programming
Socket programming-tutorial-sk
Java Socket Programming
HTTPS: All you need to know
Arduino práctico ethernet
Java sockets
Elementary TCP Sockets
Socket programming in C
Programming TCP/IP with Sockets
Socket Programming
Application Layer and Socket Programming
Ppt of socket
Network Sockets
socket programming
Lecture10
Network programming using python
Socket programming in c
Socket Programming Tutorial
Ad

Viewers also liked (20)

PDF
The Progressive Web and its New Challenges - Confoo Montréal 2017
PPTX
Refactoring vers les design patterns pyxis v2
ODP
My app is secure... I think
PPTX
Tips on solving E_TOO_MANY_THINGS_TO_LEARN with Kubernetes
PDF
The Soul in The Machine - Developing for Humans
PDF
Exploring the continuum between Cordova and React Native
PDF
Programming WebSockets - OSCON 2010
ODP
Beyond PHP - it's not (just) about the code
ODP
My app is secure... I think
PDF
Hardening Firefox for Security and Privacy
PPTX
WebSockets and Equinox OSGi in a Servlet Container - Nedelcho Delchev
ODP
Caching and tuning fun for high scalability @ phpBenelux 2011
PPTX
Let's (not) get rid of all the managers!
ODP
Practical git for developers
PPTX
PDF
Microservices Minus The Hype
PPTX
Refactoring to Design Patterns
PPTX
Designing irresistible APIs
PPTX
Training Webinar: Enterprise application performance with server push technol...
PPTX
Designing irresistible apis
The Progressive Web and its New Challenges - Confoo Montréal 2017
Refactoring vers les design patterns pyxis v2
My app is secure... I think
Tips on solving E_TOO_MANY_THINGS_TO_LEARN with Kubernetes
The Soul in The Machine - Developing for Humans
Exploring the continuum between Cordova and React Native
Programming WebSockets - OSCON 2010
Beyond PHP - it's not (just) about the code
My app is secure... I think
Hardening Firefox for Security and Privacy
WebSockets and Equinox OSGi in a Servlet Container - Nedelcho Delchev
Caching and tuning fun for high scalability @ phpBenelux 2011
Let's (not) get rid of all the managers!
Practical git for developers
Microservices Minus The Hype
Refactoring to Design Patterns
Designing irresistible APIs
Training Webinar: Enterprise application performance with server push technol...
Designing irresistible apis
Ad

Similar to Building interactivity with websockets (20)

PDF
Building interactivity with websockets
PPTX
WebSockets Everywhere: the Future Transport Protocol for Everything (Almost)
PDF
Nodejs and WebSockets
PDF
HTML5/JavaScript Communication APIs - DPC 2014
PDF
PPTX
V2 peter-lubbers-sf-jug-websocket
PPTX
GWT = easy AJAX
PPTX
Basic html5 and javascript
PPTX
DODN2009 - Jump Start Silverlight
PPTX
Creating Great Applications in SharePoint 2010 with Silverlight 4
PPT
HTML5 WebSocket: The New Network Stack for the Web
PPTX
Intro to WebSockets
PPT
Web-Technologies 26.06.2003
PPTX
Websocket technology for XPages
PPTX
Interactive web. O rly?
PPTX
Enhancing Mobile User Experience with WebSocket
PPT
A Microsoft primer for PHP devs
PDF
My adventure with WebSockets
PDF
WebKit and Blink: Bridging the Gap Between the Kernel and the HTML5 Revolution
PDF
WebKit and Blink: Bridging the Gap Between the Kernel and the HTML5 Revolutio...
Building interactivity with websockets
WebSockets Everywhere: the Future Transport Protocol for Everything (Almost)
Nodejs and WebSockets
HTML5/JavaScript Communication APIs - DPC 2014
V2 peter-lubbers-sf-jug-websocket
GWT = easy AJAX
Basic html5 and javascript
DODN2009 - Jump Start Silverlight
Creating Great Applications in SharePoint 2010 with Silverlight 4
HTML5 WebSocket: The New Network Stack for the Web
Intro to WebSockets
Web-Technologies 26.06.2003
Websocket technology for XPages
Interactive web. O rly?
Enhancing Mobile User Experience with WebSocket
A Microsoft primer for PHP devs
My adventure with WebSockets
WebKit and Blink: Bridging the Gap Between the Kernel and the HTML5 Revolution
WebKit and Blink: Bridging the Gap Between the Kernel and the HTML5 Revolutio...

More from Wim Godden (20)

PDF
Beyond php - it's not (just) about the code
PDF
Bringing bright ideas to life
PDF
The why and how of moving to php 8
PDF
The why and how of moving to php 7
PDF
My app is secure... I think
PDF
My app is secure... I think
PDF
Bringing bright ideas to life
ODP
Your app lives on the network - networking for web developers
ODP
The why and how of moving to php 7.x
ODP
The why and how of moving to php 7.x
ODP
Beyond php - it's not (just) about the code
ODP
My app is secure... I think
ODP
My app is secure... I think
ODP
The promise of asynchronous php
ODP
My app is secure... I think
ODP
Is your code ready for PHP 7 ?
ODP
Beyond php - it's not (just) about the code
ODP
My app is secure... I think
ODP
My app is secure... I think
ODP
My app is secure... I think
Beyond php - it's not (just) about the code
Bringing bright ideas to life
The why and how of moving to php 8
The why and how of moving to php 7
My app is secure... I think
My app is secure... I think
Bringing bright ideas to life
Your app lives on the network - networking for web developers
The why and how of moving to php 7.x
The why and how of moving to php 7.x
Beyond php - it's not (just) about the code
My app is secure... I think
My app is secure... I think
The promise of asynchronous php
My app is secure... I think
Is your code ready for PHP 7 ?
Beyond php - it's not (just) about the code
My app is secure... I think
My app is secure... I think
My app is secure... I think

Recently uploaded (20)

PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
PDF
NewMind AI Weekly Chronicles - August'25 Week I
DOCX
The AUB Centre for AI in Media Proposal.docx
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
KodekX | Application Modernization Development
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PDF
Encapsulation theory and applications.pdf
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
Review of recent advances in non-invasive hemoglobin estimation
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PPTX
Big Data Technologies - Introduction.pptx
PPTX
Cloud computing and distributed systems.
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
NewMind AI Weekly Chronicles - August'25 Week I
The AUB Centre for AI in Media Proposal.docx
Diabetes mellitus diagnosis method based random forest with bat algorithm
KodekX | Application Modernization Development
Building Integrated photovoltaic BIPV_UPV.pdf
Encapsulation theory and applications.pdf
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Network Security Unit 5.pdf for BCA BBA.
Review of recent advances in non-invasive hemoglobin estimation
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
Chapter 3 Spatial Domain Image Processing.pdf
Big Data Technologies - Introduction.pptx
Cloud computing and distributed systems.
Per capita expenditure prediction using model stacking based on satellite ima...
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Dropbox Q2 2025 Financial Results & Investor Presentation

Building interactivity with websockets

  • 1. Wim Godden Cu.be Solutions @wimgtr Building interactivity with WebSockets
  • 2. Who am I ? Wim Godden (@wimgtr)
  • 11. Belgium – the traffic
  • 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. Who are you ? Developers ? System engineers ? Experience with websockets ?
  • 14. OLD : Show content, wait for user to click link or button vs NEW : Show content + send user real-time updates
  • 15. Real-time = key to keep users on your platform
  • 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. 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. Long polling Client Server GET /updates GET /updates 3 2 1 4 Time {status:’1’, ...} New data arrives
  • 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. 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. 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. WebSockets - (sub)protocols Must be supported by client and server Several exist WAMP (provides PubSub) STOMP (provides messaging) Can be application specific (custom)
  • 23. WebSockets – Events & Methods Events Open Close Message Error Methods send() close()
  • 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. Uses Synchronization of data between users Multiplayer HTML5 games Live feeds Auctions Real-time updates on running processes Financial applications Messaging / chat
  • 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. 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. 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. 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. Checking if WebSocket support is enabled if (window.WebSocket) { console.log("BROWSER SUPPORTED"); } else { console.log("BROWSER NOT SUPPORTED"); }
  • 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. Time for a nice demo ;-)
  • 33. Security Always use TLS (wss:// instead of ws://) Verify the Origin header Pass along a random token to the handshake request
  • 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. 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)