SlideShare a Scribd company logo
WEBSOCKETS IN NODE.JS
ABOUT ME

•
•
•
•

GARETH MARLAND
@GARETHMARLAND
HTTPS://GITHUB.COM/GMARLAND

HTTP://WWW.DOTSTORMING.COM

(EXAMPLE CODE)
WHAT SHOULD WE CONSIDER?

•
•
•

RELIABILITY
SCALABILITY

HOSTING
HOW CAN WE IMPLEMENT THEM?

•
•
•

SOCKET.IO – MOST POPULAR BUT LEAST RELIABLE
SOCKJS – A REASONABLE ALTERNATIVE

ENGINE.IO – RELIABLE BUT LOW LEVEL
EXAMPLE – IMPLEMENTING IN ENGINE.IO
SETTING THE CONNECTION ON THE CLIENT
function connectSocket() {
socket = eio("http://localhost:8080/");
socket.onopen = function() {
socket.onmessage = function(package) {
// Handling received messages
};
};
socket.onclose = function() {
console.log("Disconnected from websocket");
connectionAttempts++;
if (connectionAttempts < 10) {
connectSockets();
}
}
}
SENDING AN OBJECT FROM THE CLIENT
var newMessage = {
owner: ‚Gareth‛,
message: ‚Hello there‛
}

var action = ‚greetings‛;
sendMessage(action, data);

function sendMessage(action, data) {
var socketPackage = { action: action, data: data }
this.socket.send(JSON.stringify(socketPackage));
}
LISTENING ON THE SERVER

socket.on('connection', function (client) {
client.send('123456');

client.on('message', function (data) {
for (var key in socket.clients ) {
if(typeof client.id !== 'undefined') {
if(key == client.id) {
continue;
}
}
socket.clients[key].send(data);
}
});
});
REMEMBER TO ALLOW CROSS DOMAINS IN
EXPRESS!

var app = express();
app.configure(function() {
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
next();
});
});
RECEIVING AN OBJECT ON THE CLIENT
function connectSockets() {
socket = eio(‘http://localhost:8080/’);
socket.onopen = function() {
socket.onmessage = function(package) {
var socketPackage = JSON.parse(package.data);
if (socketPackage.action != null) {
switch(socketPackage.action) {
case ‘greetings’:
console.log(socketPackage.data.message);
break;
}
}
};
};
}
RELIABLE WEBSOCKETS!
PROBLEMS WITH SCALING

•
•

WEBSOCKETS REQUIRE “STICKY SESSIONS”
WEBSOCKETS ONLY EXIST ON THE SERVER THE CLIENT CONNECTED TO
CLIENTS CAN’T PASS MESSAGES
BETWEEN SERVERS!
REDIS TO THE RESCUE!

•
•

REDIS HAS A PUB/SUB QUEUE
HAVE ALL OUR SERVER INSTANCES PUBLISHING AND SUBSCRIBING TO THE
QUEUE

•

PASS MESSAGES BETWEEN SERVERS USING THE QUEUE
PASSING MESSAGES WITH REDIS
PUBLISH A RECEIVED MESSAGE THROUGH
REDIS
var pub = redis.createClient();
socket.on('connection', function (client) {
client.send('123456');
client.on('message', function (data) {
try
{
pub.publish('subscription-channel', data);
}
catch (err) {
console.log("Error publishing: " + err);
}
});
});
RECEIVING A MESSAGE FROM REDIS

var sub = redis.createClient();
sub.on('ready', function() {
sub.subscribe('subscription-channel');
sub.on('message', function(channel, message) {
for( var key in socket.clients ) {
socket.clients[key].send(message);
}
});
});
SCALABLE WEBSOCKETS!
THANK YOU!

More Related Content

ZIP
Websockets at tossug
ZIP
Websocket protocol overview
KEY
Pushing the web — WebSockets
PDF
Introduction to WebSockets
PPTX
Intro to WebSockets
KEY
The HTML5 WebSocket API
PPTX
PPTX
vlavrynovych - WebSockets Presentation
Websockets at tossug
Websocket protocol overview
Pushing the web — WebSockets
Introduction to WebSockets
Intro to WebSockets
The HTML5 WebSocket API
vlavrynovych - WebSockets Presentation

What's hot (20)

PPTX
Web sockets in Java
PDF
HTTP2 is Here!
PPTX
Large scale web socket system with AWS and Web socket
PPTX
Php push notifications
ODP
Using Websockets in Play !
PDF
WebSockets wiith Scala and Play! Framework
PDF
GWT Web Socket and data serialization
PPTX
Altitude San Francisco 2018: Programming the Edge
KEY
Dancing with websocket
PPTX
Interactive web. O rly?
PDF
Using Websockets with Play!
PPTX
Elastic stack
PDF
Tips for going fast in a slow world: Michael May at OSCON 2015
PPTX
Altitude San Francisco 2018: Testing with Fastly Workshop
PDF
Async Tasks with Django Channels
PDF
Using Communication and Messaging API in the HTML5 World
PDF
Stupid Boot Tricks: using ipxe and chef to get to boot management bliss
PPTX
SPDY - or maybe HTTP2.0
PDF
WebSockets with Spring 4
PPTX
Spring + WebSocket integration
Web sockets in Java
HTTP2 is Here!
Large scale web socket system with AWS and Web socket
Php push notifications
Using Websockets in Play !
WebSockets wiith Scala and Play! Framework
GWT Web Socket and data serialization
Altitude San Francisco 2018: Programming the Edge
Dancing with websocket
Interactive web. O rly?
Using Websockets with Play!
Elastic stack
Tips for going fast in a slow world: Michael May at OSCON 2015
Altitude San Francisco 2018: Testing with Fastly Workshop
Async Tasks with Django Channels
Using Communication and Messaging API in the HTML5 World
Stupid Boot Tricks: using ipxe and chef to get to boot management bliss
SPDY - or maybe HTTP2.0
WebSockets with Spring 4
Spring + WebSocket integration
Ad

Viewers also liked (12)

PDF
Top 10 real life WebSocket use cases & experiences - Devoxx UK 2015
PDF
Real Life WebSocket Case Studies and Demos
PDF
Node.js and websockets intro
PDF
SWT Tech Sharing: Node.js + Redis
PDF
WSO2-WSF-install-manual-linux-th
PPTX
HTML5 Real Time and WebSocket Code Lab (SFHTML5, GTUGSF)
PDF
Horizontally Scaling Node.js and WebSockets
PDF
Nuts and Bolts of WebSocket Devoxx 2014
PDF
Real-time Web Application with Socket.IO, Node.js, and Redis
PDF
CouchDB Vs MongoDB
PDF
Python Performance Profiling: The Guts And The Glory
PPTX
HTML5 Real-Time and Connectivity
Top 10 real life WebSocket use cases & experiences - Devoxx UK 2015
Real Life WebSocket Case Studies and Demos
Node.js and websockets intro
SWT Tech Sharing: Node.js + Redis
WSO2-WSF-install-manual-linux-th
HTML5 Real Time and WebSocket Code Lab (SFHTML5, GTUGSF)
Horizontally Scaling Node.js and WebSockets
Nuts and Bolts of WebSocket Devoxx 2014
Real-time Web Application with Socket.IO, Node.js, and Redis
CouchDB Vs MongoDB
Python Performance Profiling: The Guts And The Glory
HTML5 Real-Time and Connectivity
Ad

Similar to Websockets in Node.js - Making them reliable and scalable (20)

PDF
Nodejs and WebSockets
PDF
DSLing your System For Scalability Testing Using Gatling - Dublin Scala User ...
PPTX
Uniface Lectures Webinar - Application & Infrastructure Security - Hardening ...
KEY
Html 5 boot camp
PPT
Frontend Servers and NGINX: What, Where and How
PDF
KSDG-iSlide App 開發心得分享
PDF
WebSocket Perspectives 2015 - Clouds, Streams, Microservices and WoT
PDF
Astricon 10 (October 2013) - SIP over WebSocket on Kamailio
KEY
Socket.io
PPTX
Introduction to Vert.x
PDF
The top 10 security issues in web applications
PDF
Banquet 36
PDF
夜宴36期《技术前哨站》
PDF
WebSockets: The Current State of the Most Valuable HTML5 API for Java Developers
PPT
HTML5 WebSocket: The New Network Stack for the Web
PDF
From Zero to Hero - Centralized Logging with Logstash & Elasticsearch
PDF
From zero to hero - Easy log centralization with Logstash and Elasticsearch
ODP
Varnish: Making eZ Publish sites fly
PDF
Intro to Sail.js
KEY
Node worshop Realtime - Socket.io
Nodejs and WebSockets
DSLing your System For Scalability Testing Using Gatling - Dublin Scala User ...
Uniface Lectures Webinar - Application & Infrastructure Security - Hardening ...
Html 5 boot camp
Frontend Servers and NGINX: What, Where and How
KSDG-iSlide App 開發心得分享
WebSocket Perspectives 2015 - Clouds, Streams, Microservices and WoT
Astricon 10 (October 2013) - SIP over WebSocket on Kamailio
Socket.io
Introduction to Vert.x
The top 10 security issues in web applications
Banquet 36
夜宴36期《技术前哨站》
WebSockets: The Current State of the Most Valuable HTML5 API for Java Developers
HTML5 WebSocket: The New Network Stack for the Web
From Zero to Hero - Centralized Logging with Logstash & Elasticsearch
From zero to hero - Easy log centralization with Logstash and Elasticsearch
Varnish: Making eZ Publish sites fly
Intro to Sail.js
Node worshop Realtime - Socket.io

Recently uploaded (20)

PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PPT
Teaching material agriculture food technology
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PDF
Spectral efficient network and resource selection model in 5G networks
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
PDF
Unlocking AI with Model Context Protocol (MCP)
PPTX
Big Data Technologies - Introduction.pptx
PPTX
sap open course for s4hana steps from ECC to s4
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
DOCX
The AUB Centre for AI in Media Proposal.docx
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
Agricultural_Statistics_at_a_Glance_2022_0.pdf
Teaching material agriculture food technology
Digital-Transformation-Roadmap-for-Companies.pptx
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
Network Security Unit 5.pdf for BCA BBA.
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
Spectral efficient network and resource selection model in 5G networks
20250228 LYD VKU AI Blended-Learning.pptx
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
Unlocking AI with Model Context Protocol (MCP)
Big Data Technologies - Introduction.pptx
sap open course for s4hana steps from ECC to s4
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
Advanced methodologies resolving dimensionality complications for autism neur...
Building Integrated photovoltaic BIPV_UPV.pdf
The AUB Centre for AI in Media Proposal.docx
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf

Websockets in Node.js - Making them reliable and scalable

  • 3. WHAT SHOULD WE CONSIDER? • • • RELIABILITY SCALABILITY HOSTING
  • 4. HOW CAN WE IMPLEMENT THEM? • • • SOCKET.IO – MOST POPULAR BUT LEAST RELIABLE SOCKJS – A REASONABLE ALTERNATIVE ENGINE.IO – RELIABLE BUT LOW LEVEL
  • 6. SETTING THE CONNECTION ON THE CLIENT function connectSocket() { socket = eio("http://localhost:8080/"); socket.onopen = function() { socket.onmessage = function(package) { // Handling received messages }; }; socket.onclose = function() { console.log("Disconnected from websocket"); connectionAttempts++; if (connectionAttempts < 10) { connectSockets(); } } }
  • 7. SENDING AN OBJECT FROM THE CLIENT var newMessage = { owner: ‚Gareth‛, message: ‚Hello there‛ } var action = ‚greetings‛; sendMessage(action, data); function sendMessage(action, data) { var socketPackage = { action: action, data: data } this.socket.send(JSON.stringify(socketPackage)); }
  • 8. LISTENING ON THE SERVER socket.on('connection', function (client) { client.send('123456'); client.on('message', function (data) { for (var key in socket.clients ) { if(typeof client.id !== 'undefined') { if(key == client.id) { continue; } } socket.clients[key].send(data); } }); });
  • 9. REMEMBER TO ALLOW CROSS DOMAINS IN EXPRESS! var app = express(); app.configure(function() { app.use(function(req, res, next) { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "X-Requested-With"); next(); }); });
  • 10. RECEIVING AN OBJECT ON THE CLIENT function connectSockets() { socket = eio(‘http://localhost:8080/’); socket.onopen = function() { socket.onmessage = function(package) { var socketPackage = JSON.parse(package.data); if (socketPackage.action != null) { switch(socketPackage.action) { case ‘greetings’: console.log(socketPackage.data.message); break; } } }; }; }
  • 12. PROBLEMS WITH SCALING • • WEBSOCKETS REQUIRE “STICKY SESSIONS” WEBSOCKETS ONLY EXIST ON THE SERVER THE CLIENT CONNECTED TO
  • 13. CLIENTS CAN’T PASS MESSAGES BETWEEN SERVERS!
  • 14. REDIS TO THE RESCUE! • • REDIS HAS A PUB/SUB QUEUE HAVE ALL OUR SERVER INSTANCES PUBLISHING AND SUBSCRIBING TO THE QUEUE • PASS MESSAGES BETWEEN SERVERS USING THE QUEUE
  • 16. PUBLISH A RECEIVED MESSAGE THROUGH REDIS var pub = redis.createClient(); socket.on('connection', function (client) { client.send('123456'); client.on('message', function (data) { try { pub.publish('subscription-channel', data); } catch (err) { console.log("Error publishing: " + err); } }); });
  • 17. RECEIVING A MESSAGE FROM REDIS var sub = redis.createClient(); sub.on('ready', function() { sub.subscribe('subscription-channel'); sub.on('message', function(channel, message) { for( var key in socket.clients ) { socket.clients[key].send(message); } }); });