SlideShare a Scribd company logo
1 of 19
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

What's hot

Interactive web. O rly?
Interactive web. O rly?Interactive web. O rly?
Interactive web. O rly?
timbc
 

What's hot (20)

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

Viewers also liked

Real Life WebSocket Case Studies and Demos
Real Life WebSocket Case Studies and DemosReal Life WebSocket Case Studies and Demos
Real Life WebSocket Case Studies and Demos
Peter Moskovits
 
Real-time Web Application with Socket.IO, Node.js, and Redis
Real-time Web Application with Socket.IO, Node.js, and RedisReal-time Web Application with Socket.IO, Node.js, and Redis
Real-time Web Application with Socket.IO, Node.js, and Redis
York Tsai
 

Viewers also liked (12)

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

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

夜宴36期《技术前哨站》
夜宴36期《技术前哨站》夜宴36期《技术前哨站》
夜宴36期《技术前哨站》
Koubei Banquet
 
WebSockets: The Current State of the Most Valuable HTML5 API for Java Developers
WebSockets: The Current State of the Most Valuable HTML5 API for Java DevelopersWebSockets: The Current State of the Most Valuable HTML5 API for Java Developers
WebSockets: The Current State of the Most Valuable HTML5 API for Java Developers
Viktor Gamov
 
Varnish: Making eZ Publish sites fly
Varnish: Making eZ Publish sites flyVarnish: Making eZ Publish sites fly
Varnish: Making eZ Publish sites fly
Peter Keung
 

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

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

Recently uploaded

Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
Enterprise Knowledge
 

Recently uploaded (20)

Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 

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); } }); });