SlideShare uma empresa Scribd logo
1 de 16
Real-time Communication
using Node.js & Socket.IO
Presenter: Vageesh Bhasin, Mindfire Solutions
Date: 20 – June – 2014
Presenter: Vageesh Bhasin, Mindfire Solutions
About Me
By Profession:

Current - Quality Analyst with Mindfire – Web Application Testing

Prior - Quality Analyst with Infosys – Database Testing
By Hobby:

Web App using Node/Express – Consultant/Developer
Contact Me:

Facebook: Link

LinkedIn: Link

My Blog: Link

Email: vageesh_bhasin@outlook.com ,
vageeshb@mindfiresolutions.com
Agenda

WebSocket
– Introduction to WebSockets
– How WebSockets work

Socket.IO
– Introduction to Socket.IO
– Using Socket.IO
– Firing events
– Listening to events

Demo on creating a small app
Presenter: Vageesh Bhasin, Mindfire Solutions
WebSockets
Introduction to WebSocket

Protocol providing full-duplex communication channel over single TCP
connection

Web was built around the idea – 'Client requests, Server fulfills'

AJAX got people started to look for bidirectional connections

Other strategies like long-polling had the problem of carry overhead,
leading to increase in latency
Presenter: Vageesh Bhasin, Mindfire Solutions
How does WebSockets Work?

Establish connection through 'WebSocket Handshake'
– Client Request
– Server Response

After handshake, initial HTTP connection is replaced by WebSocket
connection (uses same underlying TCP/IP)

Transfer data without incurring any overhead associated with requests
Presenter: Vageesh Bhasin, Mindfire Solutions
GET /chat HTTP/1.1
Host: server.example.com
Upgrade: websocket
Connection: Upgrade
Origin: http://example.com
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Socket.IO
Introduction to Socket.IO

JavaScript library for realtime web applications

Has two parts:
– Client-side – Runs on Browser
– Server-side – Runs on Server – Node.js

Primarily uses WebSocket, but can fallback to other methods like AJAX
long polling, JSONP polling

In addition to one-to-one communication as in WebSocket, it enables
broadcasting to multiple nodes
Presenter: Vageesh Bhasin, Mindfire Solutions
Using Socket.IO

With Node HTTP Server
// app.js
// Requiring Module Dependencies
var app = require('http').createServer(serveFile),
io = require('socket.io')(app),
fs = require('fs');
app.listen(3000, function () {
console.log('Server up and listening to port 3000');
});
// Handler to serve static files
function serveFile(req, res) {
fs.readFile(__dirname + '/index.html', function(err, data) {
if(err) {
res.writeHead(500);
return res.end('Error loading index.html');
}
res.writeHead(200);
return res.end(data);
});
}
// Socket.IO
io.on('connection', function (socket) {
// Event 1
socket.emit('event_1', {hello: 'world!'});
// Event 2
socket.on('event_2', function(data) {
console.log(data);
});
});
// index.html
<html>
<head>
<title>Socket.io Demo</title>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io('http://localhost');
socket.on('event_1', function (data) {
console.log(data);
socket.emit('event_2', { my: 'data' });
});
</script>
</head>
<body>
<h1>Socket.IO Demo</h1>
</body>
</html>
Using Socket.IO

With Express.JS
// Requiring Module Dependencies
var app = require('express')(),
server = app.listen(3000, function () {
console.log('Server up and listening to port 3000');
}),
io = require('socket.io').listen(server);
app.get('/', function(req, res) {
res.sendfile(__dirname + '/index.html');
});
// Socket.IO
io.on('connection', function (socket) {
// Event 1
socket.emit('event_1', {hello: 'world!'});
// Event 2
socket.on('event_2', function(data) {
console.log(data);
});
});
// index.html
<html>
<head>
<title>Socket.io Demo</title>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io('http://localhost');
socket.on('event_1', function (data) {
console.log(data);
socket.emit('event_2', { my: 'data' });
});
</script>
</head>
<body>
<h1>Socket.IO Demo</h1>
</body>
</html>
Firing Events

Individual Recipient - EMIT
– Current connected socket
– Specific Socket

Multiple Recipients – BROADCAST
– All connected nodes except the current one
– All connected nodes

Specific Channel – TO/IN
– To all connected nodes in a channel except current
– To all connected nodes in a channel
Presenter: Vageesh Bhasin, Mindfire Solutions
SYNTAX: socket.emit('eventName', "Event Data");
SYNTAX: io.sockets.socket(socketId).emit('eventName', "Event Data");
SYNTAX: socket.broadcast.emit('eventName', "Event Data");
SYNTAX: io.sockets.emit('eventName', "Event Data");
SYNTAX: socket.broadcast.to(channelName).emit('eventName', "Event Data");
SYNTAX: io.sockets.in(channelName).emit('eventName', "Event Data");
Listening to Events

Listening to events is easier as compared to firing events
Presenter: Vageesh Bhasin, Mindfire Solutions
Syntax:
socket.on('eventName', handler);
Example:
// Register a handler to listen to 'event_1'
socket.on('event_1', function (data) {
// Respond by sending message with time stamp to all nodes
io.sockets.emit('pushMessage', {
message: data.message,
time: new Date()
});
});
DEMO
Presenter: Vageesh Bhasin, Mindfire Solutions
Question and Answer
Presenter: Vageesh Bhasin, Mindfire Solutions
www.mindfiresolutions.com
https://www.facebook.com/MindfireSolutions
http://www.linkedin.com/company/mindfire-solutions
http://twitter.com/mindfires
Thank you

Mais conteúdo relacionado

Mais procurados

Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.jsRob O'Doherty
 
Node js overview
Node js overviewNode js overview
Node js overviewEyal Vardi
 
Web develop in flask
Web develop in flaskWeb develop in flask
Web develop in flaskJim Yeh
 
Design Beautiful REST + JSON APIs
Design Beautiful REST + JSON APIsDesign Beautiful REST + JSON APIs
Design Beautiful REST + JSON APIsStormpath
 
Rest & RESTful WebServices
Rest & RESTful WebServicesRest & RESTful WebServices
Rest & RESTful WebServicesPrateek Tandon
 
Client server chat application
Client server chat applicationClient server chat application
Client server chat applicationSamsil Arefin
 
OAuth2 - Introduction
OAuth2 - IntroductionOAuth2 - Introduction
OAuth2 - IntroductionKnoldus Inc.
 
Nodejs functions & modules
Nodejs functions & modulesNodejs functions & modules
Nodejs functions & modulesmonikadeshmane
 
RESTful services
RESTful servicesRESTful services
RESTful servicesgouthamrv
 
Node.js Express
Node.js  ExpressNode.js  Express
Node.js ExpressEyal Vardi
 
Node js Modules and Event Emitters
Node js Modules and Event EmittersNode js Modules and Event Emitters
Node js Modules and Event EmittersTheCreativedev Blog
 
Rest presentation
Rest  presentationRest  presentation
Rest presentationsrividhyau
 
Understanding REST
Understanding RESTUnderstanding REST
Understanding RESTNitin Pande
 

Mais procurados (20)

Node js introduction
Node js introductionNode js introduction
Node js introduction
 
Express js
Express jsExpress js
Express js
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
 
Node js overview
Node js overviewNode js overview
Node js overview
 
Express node js
Express node jsExpress node js
Express node js
 
Web develop in flask
Web develop in flaskWeb develop in flask
Web develop in flask
 
Design Beautiful REST + JSON APIs
Design Beautiful REST + JSON APIsDesign Beautiful REST + JSON APIs
Design Beautiful REST + JSON APIs
 
Rest & RESTful WebServices
Rest & RESTful WebServicesRest & RESTful WebServices
Rest & RESTful WebServices
 
Client server chat application
Client server chat applicationClient server chat application
Client server chat application
 
OAuth2 - Introduction
OAuth2 - IntroductionOAuth2 - Introduction
OAuth2 - Introduction
 
Gradle Introduction
Gradle IntroductionGradle Introduction
Gradle Introduction
 
NodeJS for Beginner
NodeJS for BeginnerNodeJS for Beginner
NodeJS for Beginner
 
Nodejs functions & modules
Nodejs functions & modulesNodejs functions & modules
Nodejs functions & modules
 
RESTful services
RESTful servicesRESTful services
RESTful services
 
Node.js Express
Node.js  ExpressNode.js  Express
Node.js Express
 
RESTful Web Services
RESTful Web ServicesRESTful Web Services
RESTful Web Services
 
Node js Modules and Event Emitters
Node js Modules and Event EmittersNode js Modules and Event Emitters
Node js Modules and Event Emitters
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
 
Rest presentation
Rest  presentationRest  presentation
Rest presentation
 
Understanding REST
Understanding RESTUnderstanding REST
Understanding REST
 

Destaque

Real time web: is there a life without socket.io and node.js?
Real time web: is there a life without socket.io and node.js?Real time web: is there a life without socket.io and node.js?
Real time web: is there a life without socket.io and node.js?Eduard Trayan
 
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 RedisYork Tsai
 
Building notification system in NodeJS + Redis
Building notification system in NodeJS + RedisBuilding notification system in NodeJS + Redis
Building notification system in NodeJS + RedisLe Duc
 
NodeJS & Socket IO on Microsoft Azure Cloud Web Sites - DWX 2014
NodeJS & Socket IO on Microsoft Azure Cloud Web Sites - DWX 2014NodeJS & Socket IO on Microsoft Azure Cloud Web Sites - DWX 2014
NodeJS & Socket IO on Microsoft Azure Cloud Web Sites - DWX 2014Stéphane ESCANDELL
 
Websocket + Redis pubsub
Websocket + Redis pubsubWebsocket + Redis pubsub
Websocket + Redis pubsubKai Hsu
 
Using Node.js to Build Great Streaming Services - HTML5 Dev Conf
Using Node.js to  Build Great  Streaming Services - HTML5 Dev ConfUsing Node.js to  Build Great  Streaming Services - HTML5 Dev Conf
Using Node.js to Build Great Streaming Services - HTML5 Dev ConfTom Croucher
 
Node.js streaming csv downloads proxy
Node.js streaming csv downloads proxyNode.js streaming csv downloads proxy
Node.js streaming csv downloads proxyIsmael Celis
 
Notifications - Building a transparent system
Notifications - Building a transparent systemNotifications - Building a transparent system
Notifications - Building a transparent systemJoão Lopes
 
Socket io - JSZurich
Socket io - JSZurichSocket io - JSZurich
Socket io - JSZurichstreunerlein
 
Node js oc meetup 2 socket io intro
Node js oc meetup 2 socket io introNode js oc meetup 2 socket io intro
Node js oc meetup 2 socket io introeddify
 
Node worshop Realtime - Socket.io
Node worshop Realtime - Socket.ioNode worshop Realtime - Socket.io
Node worshop Realtime - Socket.ioCaesar Chi
 
Better d3 charts with tdd
Better d3 charts with tddBetter d3 charts with tdd
Better d3 charts with tddMarcos Iglesias
 
Realtime web applications with ExpressJS and SocketIO
Realtime web applications with ExpressJS and SocketIORealtime web applications with ExpressJS and SocketIO
Realtime web applications with ExpressJS and SocketIOHüseyin BABAL
 
Data visualization
Data visualizationData visualization
Data visualizationsagalabo
 
Building your First MEAN App
Building your First MEAN AppBuilding your First MEAN App
Building your First MEAN AppMongoDB
 

Destaque (20)

Real time web: is there a life without socket.io and node.js?
Real time web: is there a life without socket.io and node.js?Real time web: is there a life without socket.io and node.js?
Real time web: is there a life without socket.io and node.js?
 
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
 
Building notification system in NodeJS + Redis
Building notification system in NodeJS + RedisBuilding notification system in NodeJS + Redis
Building notification system in NodeJS + Redis
 
Socket.io
Socket.ioSocket.io
Socket.io
 
NodeJS & Socket IO on Microsoft Azure Cloud Web Sites - DWX 2014
NodeJS & Socket IO on Microsoft Azure Cloud Web Sites - DWX 2014NodeJS & Socket IO on Microsoft Azure Cloud Web Sites - DWX 2014
NodeJS & Socket IO on Microsoft Azure Cloud Web Sites - DWX 2014
 
Websocket + Redis pubsub
Websocket + Redis pubsubWebsocket + Redis pubsub
Websocket + Redis pubsub
 
Using Node.js to Build Great Streaming Services - HTML5 Dev Conf
Using Node.js to  Build Great  Streaming Services - HTML5 Dev ConfUsing Node.js to  Build Great  Streaming Services - HTML5 Dev Conf
Using Node.js to Build Great Streaming Services - HTML5 Dev Conf
 
Learn node.js by building projects
Learn node.js by building projectsLearn node.js by building projects
Learn node.js by building projects
 
Node.js streaming csv downloads proxy
Node.js streaming csv downloads proxyNode.js streaming csv downloads proxy
Node.js streaming csv downloads proxy
 
Notifications - Building a transparent system
Notifications - Building a transparent systemNotifications - Building a transparent system
Notifications - Building a transparent system
 
Socket io - JSZurich
Socket io - JSZurichSocket io - JSZurich
Socket io - JSZurich
 
Node js oc meetup 2 socket io intro
Node js oc meetup 2 socket io introNode js oc meetup 2 socket io intro
Node js oc meetup 2 socket io intro
 
Node worshop Realtime - Socket.io
Node worshop Realtime - Socket.ioNode worshop Realtime - Socket.io
Node worshop Realtime - Socket.io
 
Better d3 charts with tdd
Better d3 charts with tddBetter d3 charts with tdd
Better d3 charts with tdd
 
Realtime web applications with ExpressJS and SocketIO
Realtime web applications with ExpressJS and SocketIORealtime web applications with ExpressJS and SocketIO
Realtime web applications with ExpressJS and SocketIO
 
Data visualization
Data visualizationData visualization
Data visualization
 
tea
teatea
tea
 
Transforming WebSockets
Transforming WebSocketsTransforming WebSockets
Transforming WebSockets
 
Building your First MEAN App
Building your First MEAN AppBuilding your First MEAN App
Building your First MEAN App
 
Socket.io - Intro
Socket.io - IntroSocket.io - Intro
Socket.io - Intro
 

Semelhante a Real Time Communication using Node.js and Socket.io

Message in a Bottle
Message in a BottleMessage in a Bottle
Message in a BottleZohar Arad
 
Building interactivity with websockets
Building interactivity with websocketsBuilding interactivity with websockets
Building interactivity with websocketsWim Godden
 
Restap ito uploadfilessharepoint
Restap ito uploadfilessharepointRestap ito uploadfilessharepoint
Restap ito uploadfilessharepointMAHESH NEELANNAVAR
 
Websockets talk at Rubyconf Uruguay 2010
Websockets talk at Rubyconf Uruguay 2010Websockets talk at Rubyconf Uruguay 2010
Websockets talk at Rubyconf Uruguay 2010Ismael Celis
 
Into to Node.js: Building Fast, Scaleable Network Applications
Into to Node.js: Building Fast, Scaleable Network ApplicationsInto to Node.js: Building Fast, Scaleable Network Applications
Into to Node.js: Building Fast, Scaleable Network ApplicationsFlatiron School
 
MIKE Stack Introduction - MongoDB, io.js, KendoUI, and Express
MIKE Stack Introduction - MongoDB, io.js, KendoUI, and ExpressMIKE Stack Introduction - MongoDB, io.js, KendoUI, and Express
MIKE Stack Introduction - MongoDB, io.js, KendoUI, and ExpressCharlie Key
 
Web APIs & Apps - Mozilla
Web APIs & Apps - MozillaWeb APIs & Apps - Mozilla
Web APIs & Apps - MozillaRobert Nyman
 
HTML5 tutorial: canvas, offfline & sockets
HTML5 tutorial: canvas, offfline & socketsHTML5 tutorial: canvas, offfline & sockets
HTML5 tutorial: canvas, offfline & socketsRemy Sharp
 
Nodejs and WebSockets
Nodejs and WebSocketsNodejs and WebSockets
Nodejs and WebSocketsGonzalo Ayuso
 
Node.js Workshop - Sela SDP 2015
Node.js Workshop  - Sela SDP 2015Node.js Workshop  - Sela SDP 2015
Node.js Workshop - Sela SDP 2015Nir Noy
 
Denys Serhiienko "ASGI in depth"
Denys Serhiienko "ASGI in depth"Denys Serhiienko "ASGI in depth"
Denys Serhiienko "ASGI in depth"Fwdays
 
Cloudbase.io MoSync Reload Course
Cloudbase.io MoSync Reload CourseCloudbase.io MoSync Reload Course
Cloudbase.io MoSync Reload Coursecloudbase.io
 
Quick Fetch API Introduction
Quick Fetch API IntroductionQuick Fetch API Introduction
Quick Fetch API IntroductionChris Love
 
HTML5: huh, what is it good for?
HTML5: huh, what is it good for?HTML5: huh, what is it good for?
HTML5: huh, what is it good for?Remy Sharp
 
Browser security
Browser securityBrowser security
Browser securityUday Anand
 
Service Worker - Reliability bits
Service Worker - Reliability bitsService Worker - Reliability bits
Service Worker - Reliability bitsjungkees
 

Semelhante a Real Time Communication using Node.js and Socket.io (20)

Message in a Bottle
Message in a BottleMessage in a Bottle
Message in a Bottle
 
Building interactivity with websockets
Building interactivity with websocketsBuilding interactivity with websockets
Building interactivity with websockets
 
RESTAPI_SPHOSTED_APP
RESTAPI_SPHOSTED_APPRESTAPI_SPHOSTED_APP
RESTAPI_SPHOSTED_APP
 
Restap ito uploadfilessharepoint
Restap ito uploadfilessharepointRestap ito uploadfilessharepoint
Restap ito uploadfilessharepoint
 
Pushing the Web: Interesting things to Know
Pushing the Web: Interesting things to KnowPushing the Web: Interesting things to Know
Pushing the Web: Interesting things to Know
 
Websockets talk at Rubyconf Uruguay 2010
Websockets talk at Rubyconf Uruguay 2010Websockets talk at Rubyconf Uruguay 2010
Websockets talk at Rubyconf Uruguay 2010
 
Into to Node.js: Building Fast, Scaleable Network Applications
Into to Node.js: Building Fast, Scaleable Network ApplicationsInto to Node.js: Building Fast, Scaleable Network Applications
Into to Node.js: Building Fast, Scaleable Network Applications
 
MIKE Stack Introduction - MongoDB, io.js, KendoUI, and Express
MIKE Stack Introduction - MongoDB, io.js, KendoUI, and ExpressMIKE Stack Introduction - MongoDB, io.js, KendoUI, and Express
MIKE Stack Introduction - MongoDB, io.js, KendoUI, and Express
 
Web APIs & Apps - Mozilla
Web APIs & Apps - MozillaWeb APIs & Apps - Mozilla
Web APIs & Apps - Mozilla
 
HTML5 tutorial: canvas, offfline & sockets
HTML5 tutorial: canvas, offfline & socketsHTML5 tutorial: canvas, offfline & sockets
HTML5 tutorial: canvas, offfline & sockets
 
Nodejs and WebSockets
Nodejs and WebSocketsNodejs and WebSockets
Nodejs and WebSockets
 
HTML5 WebWorks
HTML5 WebWorksHTML5 WebWorks
HTML5 WebWorks
 
Node.js Workshop - Sela SDP 2015
Node.js Workshop  - Sela SDP 2015Node.js Workshop  - Sela SDP 2015
Node.js Workshop - Sela SDP 2015
 
Denys Serhiienko "ASGI in depth"
Denys Serhiienko "ASGI in depth"Denys Serhiienko "ASGI in depth"
Denys Serhiienko "ASGI in depth"
 
Cloudbase.io MoSync Reload Course
Cloudbase.io MoSync Reload CourseCloudbase.io MoSync Reload Course
Cloudbase.io MoSync Reload Course
 
Quick Fetch API Introduction
Quick Fetch API IntroductionQuick Fetch API Introduction
Quick Fetch API Introduction
 
SocketStream
SocketStreamSocketStream
SocketStream
 
HTML5: huh, what is it good for?
HTML5: huh, what is it good for?HTML5: huh, what is it good for?
HTML5: huh, what is it good for?
 
Browser security
Browser securityBrowser security
Browser security
 
Service Worker - Reliability bits
Service Worker - Reliability bitsService Worker - Reliability bits
Service Worker - Reliability bits
 

Mais de Mindfire Solutions (20)

Physician Search and Review
Physician Search and ReviewPhysician Search and Review
Physician Search and Review
 
diet management app
diet management appdiet management app
diet management app
 
Business Technology Solution
Business Technology SolutionBusiness Technology Solution
Business Technology Solution
 
Remote Health Monitoring
Remote Health MonitoringRemote Health Monitoring
Remote Health Monitoring
 
Influencer Marketing Solution
Influencer Marketing SolutionInfluencer Marketing Solution
Influencer Marketing Solution
 
ELMAH
ELMAHELMAH
ELMAH
 
High Availability of Azure Applications
High Availability of Azure ApplicationsHigh Availability of Azure Applications
High Availability of Azure Applications
 
IOT Hands On
IOT Hands OnIOT Hands On
IOT Hands On
 
Glimpse of Loops Vs Set
Glimpse of Loops Vs SetGlimpse of Loops Vs Set
Glimpse of Loops Vs Set
 
Oracle Sql Developer-Getting Started
Oracle Sql Developer-Getting StartedOracle Sql Developer-Getting Started
Oracle Sql Developer-Getting Started
 
Adaptive Layout In iOS 8
Adaptive Layout In iOS 8Adaptive Layout In iOS 8
Adaptive Layout In iOS 8
 
Introduction to Auto-layout : iOS/Mac
Introduction to Auto-layout : iOS/MacIntroduction to Auto-layout : iOS/Mac
Introduction to Auto-layout : iOS/Mac
 
LINQPad - utility Tool
LINQPad - utility ToolLINQPad - utility Tool
LINQPad - utility Tool
 
Get started with watch kit development
Get started with watch kit developmentGet started with watch kit development
Get started with watch kit development
 
Swift vs Objective-C
Swift vs Objective-CSwift vs Objective-C
Swift vs Objective-C
 
Material Design in Android
Material Design in AndroidMaterial Design in Android
Material Design in Android
 
Introduction to OData
Introduction to ODataIntroduction to OData
Introduction to OData
 
Ext js Part 2- MVC
Ext js Part 2- MVCExt js Part 2- MVC
Ext js Part 2- MVC
 
ExtJs Basic Part-1
ExtJs Basic Part-1ExtJs Basic Part-1
ExtJs Basic Part-1
 
Spring Security Introduction
Spring Security IntroductionSpring Security Introduction
Spring Security Introduction
 

Último

Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...aditisharan08
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptkotipi9215
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfkalichargn70th171
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 

Último (20)

Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.ppt
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
Exploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the ProcessExploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the Process
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 

Real Time Communication using Node.js and Socket.io

  • 1. Real-time Communication using Node.js & Socket.IO Presenter: Vageesh Bhasin, Mindfire Solutions Date: 20 – June – 2014
  • 2. Presenter: Vageesh Bhasin, Mindfire Solutions About Me By Profession:  Current - Quality Analyst with Mindfire – Web Application Testing  Prior - Quality Analyst with Infosys – Database Testing By Hobby:  Web App using Node/Express – Consultant/Developer Contact Me:  Facebook: Link  LinkedIn: Link  My Blog: Link  Email: vageesh_bhasin@outlook.com , vageeshb@mindfiresolutions.com
  • 3. Agenda  WebSocket – Introduction to WebSockets – How WebSockets work  Socket.IO – Introduction to Socket.IO – Using Socket.IO – Firing events – Listening to events  Demo on creating a small app Presenter: Vageesh Bhasin, Mindfire Solutions
  • 5. Introduction to WebSocket  Protocol providing full-duplex communication channel over single TCP connection  Web was built around the idea – 'Client requests, Server fulfills'  AJAX got people started to look for bidirectional connections  Other strategies like long-polling had the problem of carry overhead, leading to increase in latency Presenter: Vageesh Bhasin, Mindfire Solutions
  • 6. How does WebSockets Work?  Establish connection through 'WebSocket Handshake' – Client Request – Server Response  After handshake, initial HTTP connection is replaced by WebSocket connection (uses same underlying TCP/IP)  Transfer data without incurring any overhead associated with requests Presenter: Vageesh Bhasin, Mindfire Solutions GET /chat HTTP/1.1 Host: server.example.com Upgrade: websocket Connection: Upgrade Origin: http://example.com HTTP/1.1 101 Switching Protocols Upgrade: websocket Connection: Upgrade
  • 8. Introduction to Socket.IO  JavaScript library for realtime web applications  Has two parts: – Client-side – Runs on Browser – Server-side – Runs on Server – Node.js  Primarily uses WebSocket, but can fallback to other methods like AJAX long polling, JSONP polling  In addition to one-to-one communication as in WebSocket, it enables broadcasting to multiple nodes Presenter: Vageesh Bhasin, Mindfire Solutions
  • 9. Using Socket.IO  With Node HTTP Server // app.js // Requiring Module Dependencies var app = require('http').createServer(serveFile), io = require('socket.io')(app), fs = require('fs'); app.listen(3000, function () { console.log('Server up and listening to port 3000'); }); // Handler to serve static files function serveFile(req, res) { fs.readFile(__dirname + '/index.html', function(err, data) { if(err) { res.writeHead(500); return res.end('Error loading index.html'); } res.writeHead(200); return res.end(data); }); } // Socket.IO io.on('connection', function (socket) { // Event 1 socket.emit('event_1', {hello: 'world!'}); // Event 2 socket.on('event_2', function(data) { console.log(data); }); }); // index.html <html> <head> <title>Socket.io Demo</title> <script src="/socket.io/socket.io.js"></script> <script> var socket = io('http://localhost'); socket.on('event_1', function (data) { console.log(data); socket.emit('event_2', { my: 'data' }); }); </script> </head> <body> <h1>Socket.IO Demo</h1> </body> </html>
  • 10. Using Socket.IO  With Express.JS // Requiring Module Dependencies var app = require('express')(), server = app.listen(3000, function () { console.log('Server up and listening to port 3000'); }), io = require('socket.io').listen(server); app.get('/', function(req, res) { res.sendfile(__dirname + '/index.html'); }); // Socket.IO io.on('connection', function (socket) { // Event 1 socket.emit('event_1', {hello: 'world!'}); // Event 2 socket.on('event_2', function(data) { console.log(data); }); }); // index.html <html> <head> <title>Socket.io Demo</title> <script src="/socket.io/socket.io.js"></script> <script> var socket = io('http://localhost'); socket.on('event_1', function (data) { console.log(data); socket.emit('event_2', { my: 'data' }); }); </script> </head> <body> <h1>Socket.IO Demo</h1> </body> </html>
  • 11. Firing Events  Individual Recipient - EMIT – Current connected socket – Specific Socket  Multiple Recipients – BROADCAST – All connected nodes except the current one – All connected nodes  Specific Channel – TO/IN – To all connected nodes in a channel except current – To all connected nodes in a channel Presenter: Vageesh Bhasin, Mindfire Solutions SYNTAX: socket.emit('eventName', "Event Data"); SYNTAX: io.sockets.socket(socketId).emit('eventName', "Event Data"); SYNTAX: socket.broadcast.emit('eventName', "Event Data"); SYNTAX: io.sockets.emit('eventName', "Event Data"); SYNTAX: socket.broadcast.to(channelName).emit('eventName', "Event Data"); SYNTAX: io.sockets.in(channelName).emit('eventName', "Event Data");
  • 12. Listening to Events  Listening to events is easier as compared to firing events Presenter: Vageesh Bhasin, Mindfire Solutions Syntax: socket.on('eventName', handler); Example: // Register a handler to listen to 'event_1' socket.on('event_1', function (data) { // Respond by sending message with time stamp to all nodes io.sockets.emit('pushMessage', { message: data.message, time: new Date() }); });
  • 13. DEMO Presenter: Vageesh Bhasin, Mindfire Solutions
  • 14. Question and Answer Presenter: Vageesh Bhasin, Mindfire Solutions