SlideShare a Scribd company logo
1 of 30
Download to read offline
socket.io
an unconventional tutorial
PART 1
Hello!
I am Andrea Tarquini
I am a full stack developer (mainly
working with MEAN stack) and an IT
(security) geek and fan.
Follow me at:
@h4t0n
h4t0n
Andrea Tarquini
blog.h4t0n.com
socket.io an unconventional tutorial -- PART 1
We’ll see a socket.io simple introduction:
1. how it works (hacker style)
○ taking a look at what happens within the browser
2. get started with socket.io
○ some references to good starting points for
beginners (but not followed by this tutorial)
3. how it works (engineer style)
○ writing some application examples from the official
documentation
Before starting… What is Socket.io ?
■ Essentially a fast real time engine
■ It enables real-time bidirectional event-
based communication
■ It works on every platform, browser, device.
■ Mainly used for
○ Instant messaging and chat
○ Document collaboration
○ Binary streaming (image/video/audio… )
from version 1.0
1.
How it works (hacker style)
Let’s start taking a look at what
happens within the browser
So let’s open socket.io with the Chrome Dev Console
Let’s type /socket.io on the network filter
There are two socket.io realtime connections
One for slack
There are two socket.io realtime connections
One for tweets
There are some strange requests….
Both the socket.io connections
■ start with xhr-polling (long polling)
■ then switch to websocket transport (if supported)
[more info here]
Let’s see the web socket data for tweets..
We have some control data and we can also
identify the tweets seen in the home page
Let’s play with the chat to understand exchanged data...
I talked a bit in the chat…
… but let’s see what happened using the console
A lot of data → control, messages and events
What have we learned from the client (browser)?
Events
The client listen to events
notifications and also emits
events. In the chat example,
events are:
■ client → server
○ typing
○ stop typing
○ new message
■ server → client
○ typing
○ user left
○ new message
Messages
Each event (listened or
emitted) can have an
associated message that is
the most important content:
■ strings
■ objects / arrays
■ but also (images, audio,...)
○ Buffers
○ Blobs
○ ArrayBuffers
○ Files
If you followed me, you have understood
events and messages without reading any
line of code or documentation.
But if you want to play more with the browser I suggest to
take a look at the source code and to use the console with
localStorage.debug=”socket.io-client:*”
to see debug messages (NB: reload the page)
That’s all ?
Namespaces
Can be used to assign
different endpoints (paths) to
sockets (default is root / )
It is often used to separate
concerns within an
application. For example:
■ notification namespace
■ chat namespace
Room
Inside a namespace (also the
root) you can define channels
that a socket can join or
leave. For example
■ a channel for a restricted
chat or team
!!!NO!!! The Server has its roles, it can be used to group
sockets in namespaces and rooms
We don’t see here. We’ll see
both in PART 2 !!!!
2.
Get Started with socket.io
Let’s start with the chat application
at socket.io/get-started/chat/
The “Hello Word” for Socket.IO !!!!
The socket.io chat application is recommended for beginners to
Socket.IO or Node.js
Follow the tutorial at socket.io/get-started/chat could be very
useful for all and it is highly recommended.
You can get the full chat example code also on Github:
github.com/rauchg/chat-example
ATTENTION!!!!! In the following slides we won’t follow the
chat application, we’ll work with the documentation.
3.
How it works (engineer style)
Let’s follow the official socket.io
documentation at socket.io/docs/
Get the sample code from documentation...
You can write your own app with the code
available at socket.io/docs or you can get
and run the code from socket.io-sample
github repository, which contains a list of
samples ready to be executed.
express-sample1 contains the simplest example you can find
on socket.io/docs
… code from express-sample1: The Server
// express-sample1/server.js
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
server.listen(8080, function () {
var port = server.address().port;
console.log('Example app listening on port', port);
});
app.get('/', function (req, res) {
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function (socket) {
socket.emit('news', {
hello: 'world'
});
socket.on('my other event', function (data) {
console.log(data);
});
});
Require dependencies and use socket.io with the
same express Server
Both express and socket.io listen connection on
port 8080 (default host is 0.0.0.0)
Express is used to easily serve the index page
When a client connects, we have a socket instance
that can be used to listen/emit event messages:
● the server emit a message (hello world
object) on the “news” event (only to the just
connected socket)
● the server listen to messages coming from
the “my other event” event
… code from express-sample1: The index (html page)
<!-- index.html -->
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost:8080');
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
});
</script>
GET the library from the server (it is
automatically served by socket.io)
Connect to socket.io and get a socket to use for
the event based communication
When the client connects, we have a socket
instance that can be used to listen/emit event
messages:
● the client listen to messages coming from the
“news” event
● once one is received the client emit a
message (my data object) to “my other
event” event
… code from express-sample1: run the sample
DOWNLOAD THE SAMPLES AND INSTALL NODE DEPENDENCIES
$ git clone git@github.com:h4t0n/socket.io-sample.git
$ cd socket.io-sample
# install package.json dependencies
# including socket.io,express,...
$ npm install
RUN EXPRESS-SAMPLE1
$ node express-sample1/server.js
● now open your browser at http://127.0.0.1:8080
● take a look at browser and server console
… code from express-sample1: another type of client
// client.js
var io = require('socket.io-client');
var socket = io.connect('http://localhost:
8080');
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
});
ATTENTION!!!!! To interact with a socket.io server we don’t need a
browser at all. We can use a standalone Node.js script client.
We have to use the socket.io-client module (already installed in the
previous slide command $ npm install )
TODO!! Run the client more times from several
terminal and take a look at the server console.
From the example we have seen how to:
■ create a socket.io server
■ connect to the server by using a browser or a
standalone node app (script)
■ listen and emit event messages
○ from a single client to the server and vice versa
SO… VERY SIMPLE AND BASIC CONCEPTS...
.. .BUT THERE IS MUCH MORE !!!!!!!
Socket.io allows also to:
■ emit messages to all the connected clients
■ broadcast messages
○ sending message to everyone else except the socket that
start the communication (that emit an event)
■ send volatile messages
■ send and get acknowledgments
■ listen to other default events
○ such as the disconnect one
■ be used just as a cross browser websocket
○ without events or other socket.io additions
The socket.io/docs overview treats these concepts...
express-sample2 is a simple web app that
easily shows other most used features:
■ broadcast messages
■ emit messages to all connected clients
■ listen to disconnect event
■ emit messages without using socket.io
events (just as a cross browser websocket)
…or you can take a look at express-sample2 from socket.
io-sample repository
!!!! SO PLAY WITH EXPRESS-SAMPLE2 !!!
■ namespaces
■ rooms
■ middlewares
■ etcetera…
WE’LL SEE MORE FEATURES AND EXAMPLES IN THE
TUTORIAL PART 2
Thanks!
Any questions?
You can find me at:
@h4t0n
h4t0n
Andrea Tarquini
blog.h4t0n.com

More Related Content

What's hot

HTTP HOST header attacks
HTTP HOST header attacksHTTP HOST header attacks
HTTP HOST header attacksDefconRussia
 
AppDynamics Custom Transaction Correlation
 AppDynamics Custom Transaction Correlation AppDynamics Custom Transaction Correlation
AppDynamics Custom Transaction CorrelationAppDynamics
 
Using Sinatra to Build REST APIs in Ruby
Using Sinatra to Build REST APIs in RubyUsing Sinatra to Build REST APIs in Ruby
Using Sinatra to Build REST APIs in RubyLaunchAny
 
What Is Express JS?
What Is Express JS?What Is Express JS?
What Is Express JS?Simplilearn
 
Express JS Middleware Tutorial
Express JS Middleware TutorialExpress JS Middleware Tutorial
Express JS Middleware TutorialSimplilearn
 
What’s wrong with WebSocket APIs? Unveiling vulnerabilities in WebSocket APIs.
What’s wrong with WebSocket APIs? Unveiling vulnerabilities in WebSocket APIs.What’s wrong with WebSocket APIs? Unveiling vulnerabilities in WebSocket APIs.
What’s wrong with WebSocket APIs? Unveiling vulnerabilities in WebSocket APIs.Mikhail Egorov
 
REST API and CRUD
REST API and CRUDREST API and CRUD
REST API and CRUDPrem Sanil
 
Ajax ppt - 32 slides
Ajax ppt - 32 slidesAjax ppt - 32 slides
Ajax ppt - 32 slidesSmithss25
 
Module design pattern i.e. express js
Module design pattern i.e. express jsModule design pattern i.e. express js
Module design pattern i.e. express jsAhmed Assaf
 
Android Application Penetration Testing - Mohammed Adam
Android Application Penetration Testing - Mohammed AdamAndroid Application Penetration Testing - Mohammed Adam
Android Application Penetration Testing - Mohammed AdamMohammed Adam
 
Secure Code Warrior - NoSQL injection
Secure Code Warrior - NoSQL injectionSecure Code Warrior - NoSQL injection
Secure Code Warrior - NoSQL injectionSecure Code Warrior
 
OpenAPI 3.0, And What It Means for the Future of Swagger
OpenAPI 3.0, And What It Means for the Future of SwaggerOpenAPI 3.0, And What It Means for the Future of Swagger
OpenAPI 3.0, And What It Means for the Future of SwaggerSmartBear
 
Learn REST in 18 Slides
Learn REST in 18 SlidesLearn REST in 18 Slides
Learn REST in 18 SlidesSuraj Gupta
 
Node.js Socket.IO
Node.js  Socket.IONode.js  Socket.IO
Node.js Socket.IOEyal Vardi
 

What's hot (20)

HTTP HOST header attacks
HTTP HOST header attacksHTTP HOST header attacks
HTTP HOST header attacks
 
AppDynamics Custom Transaction Correlation
 AppDynamics Custom Transaction Correlation AppDynamics Custom Transaction Correlation
AppDynamics Custom Transaction Correlation
 
Using Sinatra to Build REST APIs in Ruby
Using Sinatra to Build REST APIs in RubyUsing Sinatra to Build REST APIs in Ruby
Using Sinatra to Build REST APIs in Ruby
 
What Is Express JS?
What Is Express JS?What Is Express JS?
What Is Express JS?
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
 
Node.js Express Framework
Node.js Express FrameworkNode.js Express Framework
Node.js Express Framework
 
Express node js
Express node jsExpress node js
Express node js
 
Express JS Middleware Tutorial
Express JS Middleware TutorialExpress JS Middleware Tutorial
Express JS Middleware Tutorial
 
Express JS
Express JSExpress JS
Express JS
 
What’s wrong with WebSocket APIs? Unveiling vulnerabilities in WebSocket APIs.
What’s wrong with WebSocket APIs? Unveiling vulnerabilities in WebSocket APIs.What’s wrong with WebSocket APIs? Unveiling vulnerabilities in WebSocket APIs.
What’s wrong with WebSocket APIs? Unveiling vulnerabilities in WebSocket APIs.
 
REST API and CRUD
REST API and CRUDREST API and CRUD
REST API and CRUD
 
Ajax ppt - 32 slides
Ajax ppt - 32 slidesAjax ppt - 32 slides
Ajax ppt - 32 slides
 
Rest api with node js and express
Rest api with node js and expressRest api with node js and express
Rest api with node js and express
 
Module design pattern i.e. express js
Module design pattern i.e. express jsModule design pattern i.e. express js
Module design pattern i.e. express js
 
Android Application Penetration Testing - Mohammed Adam
Android Application Penetration Testing - Mohammed AdamAndroid Application Penetration Testing - Mohammed Adam
Android Application Penetration Testing - Mohammed Adam
 
Secure Code Warrior - NoSQL injection
Secure Code Warrior - NoSQL injectionSecure Code Warrior - NoSQL injection
Secure Code Warrior - NoSQL injection
 
JavaScript
JavaScriptJavaScript
JavaScript
 
OpenAPI 3.0, And What It Means for the Future of Swagger
OpenAPI 3.0, And What It Means for the Future of SwaggerOpenAPI 3.0, And What It Means for the Future of Swagger
OpenAPI 3.0, And What It Means for the Future of Swagger
 
Learn REST in 18 Slides
Learn REST in 18 SlidesLearn REST in 18 Slides
Learn REST in 18 Slides
 
Node.js Socket.IO
Node.js  Socket.IONode.js  Socket.IO
Node.js Socket.IO
 

Viewers also liked

Going real time with Socket.io
Going real time with Socket.ioGoing real time with Socket.io
Going real time with Socket.ioArnout Kazemier
 
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
 
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
 
Socket io - JSZurich
Socket io - JSZurichSocket io - JSZurich
Socket io - JSZurichstreunerlein
 
Node worshop Realtime - Socket.io
Node worshop Realtime - Socket.ioNode worshop Realtime - Socket.io
Node worshop Realtime - Socket.ioCaesar Chi
 
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
 
Better d3 charts with tdd
Better d3 charts with tddBetter d3 charts with tdd
Better d3 charts with tddMarcos Iglesias
 
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
 
Web in real time - technical project - socket.io
Web in real time - technical project - socket.ioWeb in real time - technical project - socket.io
Web in real time - technical project - socket.ioThomas Ferney
 
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
 
Socket.IO - Alternative Ways for Real-time Application
Socket.IO - Alternative Ways for Real-time ApplicationSocket.IO - Alternative Ways for Real-time Application
Socket.IO - Alternative Ways for Real-time ApplicationVorakamol Choonhasakulchok
 
Fun with D3.js: Data Visualization Eye Candy with Streaming JSON
Fun with D3.js: Data Visualization Eye Candy with Streaming JSONFun with D3.js: Data Visualization Eye Candy with Streaming JSON
Fun with D3.js: Data Visualization Eye Candy with Streaming JSONTomomi Imura
 
Practical Use of MongoDB for Node.js
Practical Use of MongoDB for Node.jsPractical Use of MongoDB for Node.js
Practical Use of MongoDB for Node.jsasync_io
 

Viewers also liked (20)

Socket.IO
Socket.IOSocket.IO
Socket.IO
 
Going real time with Socket.io
Going real time with Socket.ioGoing real time with Socket.io
Going real time with Socket.io
 
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
 
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
 
Socket io - JSZurich
Socket io - JSZurichSocket io - JSZurich
Socket io - JSZurich
 
Node worshop Realtime - Socket.io
Node worshop Realtime - Socket.ioNode worshop Realtime - Socket.io
Node worshop Realtime - Socket.io
 
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
 
Better d3 charts with tdd
Better d3 charts with tddBetter d3 charts with tdd
Better d3 charts with tdd
 
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
 
Web in real time - technical project - socket.io
Web in real time - technical project - socket.ioWeb in real time - technical project - socket.io
Web in real time - technical project - 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
 
Web socket with php v2
Web socket with php v2Web socket with php v2
Web socket with php v2
 
Socket.IO - Alternative Ways for Real-time Application
Socket.IO - Alternative Ways for Real-time ApplicationSocket.IO - Alternative Ways for Real-time Application
Socket.IO - Alternative Ways for Real-time Application
 
Socket Programming
Socket ProgrammingSocket Programming
Socket Programming
 
Fun with D3.js: Data Visualization Eye Candy with Streaming JSON
Fun with D3.js: Data Visualization Eye Candy with Streaming JSONFun with D3.js: Data Visualization Eye Candy with Streaming JSON
Fun with D3.js: Data Visualization Eye Candy with Streaming JSON
 
Practical Use of MongoDB for Node.js
Practical Use of MongoDB for Node.jsPractical Use of MongoDB for Node.js
Practical Use of MongoDB for Node.js
 
Socket.io
Socket.ioSocket.io
Socket.io
 

Similar to Socket.io (part 1)

Tornado Web Server Internals
Tornado Web Server InternalsTornado Web Server Internals
Tornado Web Server InternalsPraveen Gollakota
 
How to create multiprocess server on windows with ruby - rubykaigi2016 Ritta ...
How to create multiprocess server on windows with ruby - rubykaigi2016 Ritta ...How to create multiprocess server on windows with ruby - rubykaigi2016 Ritta ...
How to create multiprocess server on windows with ruby - rubykaigi2016 Ritta ...Ritta Narita
 
Exploring the Internet of Things Using Ruby
Exploring the Internet of Things Using RubyExploring the Internet of Things Using Ruby
Exploring the Internet of Things Using RubyMike Hagedorn
 
node.js: Javascript's in your backend
node.js: Javascript's in your backendnode.js: Javascript's in your backend
node.js: Javascript's in your backendDavid Padbury
 
TCP Sockets Tutor maXbox starter26
TCP Sockets Tutor maXbox starter26TCP Sockets Tutor maXbox starter26
TCP Sockets Tutor maXbox starter26Max Kleiner
 
Exploring Async PHP (SF Live Berlin 2019)
Exploring Async PHP (SF Live Berlin 2019)Exploring Async PHP (SF Live Berlin 2019)
Exploring Async PHP (SF Live Berlin 2019)dantleech
 
Original slides from Ryan Dahl's NodeJs intro talk
Original slides from Ryan Dahl's NodeJs intro talkOriginal slides from Ryan Dahl's NodeJs intro talk
Original slides from Ryan Dahl's NodeJs intro talkAarti Parikh
 
Ransomware for fun and non-profit
Ransomware for fun and non-profitRansomware for fun and non-profit
Ransomware for fun and non-profitYouness Zougar
 
soft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.jssoft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.jssoft-shake.ch
 
Node.js for Rubists
Node.js for RubistsNode.js for Rubists
Node.js for RubistsSagiv Ofek
 
How to build a chat application with react js, nodejs, and socket.io
How to build a chat application with react js, nodejs, and socket.ioHow to build a chat application with react js, nodejs, and socket.io
How to build a chat application with react js, nodejs, and socket.ioKaty Slemon
 
Java Networking
Java NetworkingJava Networking
Java NetworkingSunil OS
 
maXbox starter30 Web of Things
maXbox starter30 Web of ThingsmaXbox starter30 Web of Things
maXbox starter30 Web of ThingsMax Kleiner
 

Similar to Socket.io (part 1) (20)

Tornado Web Server Internals
Tornado Web Server InternalsTornado Web Server Internals
Tornado Web Server Internals
 
Book
BookBook
Book
 
Python networking
Python networkingPython networking
Python networking
 
A.java
A.javaA.java
A.java
 
How to create multiprocess server on windows with ruby - rubykaigi2016 Ritta ...
How to create multiprocess server on windows with ruby - rubykaigi2016 Ritta ...How to create multiprocess server on windows with ruby - rubykaigi2016 Ritta ...
How to create multiprocess server on windows with ruby - rubykaigi2016 Ritta ...
 
Exploring the Internet of Things Using Ruby
Exploring the Internet of Things Using RubyExploring the Internet of Things Using Ruby
Exploring the Internet of Things Using Ruby
 
node.js: Javascript's in your backend
node.js: Javascript's in your backendnode.js: Javascript's in your backend
node.js: Javascript's in your backend
 
TCP Sockets Tutor maXbox starter26
TCP Sockets Tutor maXbox starter26TCP Sockets Tutor maXbox starter26
TCP Sockets Tutor maXbox starter26
 
Exploring Async PHP (SF Live Berlin 2019)
Exploring Async PHP (SF Live Berlin 2019)Exploring Async PHP (SF Live Berlin 2019)
Exploring Async PHP (SF Live Berlin 2019)
 
Original slides from Ryan Dahl's NodeJs intro talk
Original slides from Ryan Dahl's NodeJs intro talkOriginal slides from Ryan Dahl's NodeJs intro talk
Original slides from Ryan Dahl's NodeJs intro talk
 
Java sockets
Java socketsJava sockets
Java sockets
 
Ransomware for fun and non-profit
Ransomware for fun and non-profitRansomware for fun and non-profit
Ransomware for fun and non-profit
 
Node.js essentials
 Node.js essentials Node.js essentials
Node.js essentials
 
Proposal
ProposalProposal
Proposal
 
soft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.jssoft-shake.ch - Hands on Node.js
soft-shake.ch - Hands on Node.js
 
Node.js for Rubists
Node.js for RubistsNode.js for Rubists
Node.js for Rubists
 
How to build a chat application with react js, nodejs, and socket.io
How to build a chat application with react js, nodejs, and socket.ioHow to build a chat application with react js, nodejs, and socket.io
How to build a chat application with react js, nodejs, and socket.io
 
Java Networking
Java NetworkingJava Networking
Java Networking
 
Python, do you even async?
Python, do you even async?Python, do you even async?
Python, do you even async?
 
maXbox starter30 Web of Things
maXbox starter30 Web of ThingsmaXbox starter30 Web of Things
maXbox starter30 Web of Things
 

Recently uploaded

Story Board.pptxrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr
Story Board.pptxrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrStory Board.pptxrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr
Story Board.pptxrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrHenryBriggs2
 
原版制作美国爱荷华大学毕业证(iowa毕业证书)学位证网上存档可查
原版制作美国爱荷华大学毕业证(iowa毕业证书)学位证网上存档可查原版制作美国爱荷华大学毕业证(iowa毕业证书)学位证网上存档可查
原版制作美国爱荷华大学毕业证(iowa毕业证书)学位证网上存档可查ydyuyu
 
哪里办理美国迈阿密大学毕业证(本硕)umiami在读证明存档可查
哪里办理美国迈阿密大学毕业证(本硕)umiami在读证明存档可查哪里办理美国迈阿密大学毕业证(本硕)umiami在读证明存档可查
哪里办理美国迈阿密大学毕业证(本硕)umiami在读证明存档可查ydyuyu
 
PowerDirector Explination Process...pptx
PowerDirector Explination Process...pptxPowerDirector Explination Process...pptx
PowerDirector Explination Process...pptxgalaxypingy
 
Power point inglese - educazione civica di Nuria Iuzzolino
Power point inglese - educazione civica di Nuria IuzzolinoPower point inglese - educazione civica di Nuria Iuzzolino
Power point inglese - educazione civica di Nuria Iuzzolinonuriaiuzzolino1
 
"Boost Your Digital Presence: Partner with a Leading SEO Agency"
"Boost Your Digital Presence: Partner with a Leading SEO Agency""Boost Your Digital Presence: Partner with a Leading SEO Agency"
"Boost Your Digital Presence: Partner with a Leading SEO Agency"growthgrids
 
75539-Cyber Security Challenges PPT.pptx
75539-Cyber Security Challenges PPT.pptx75539-Cyber Security Challenges PPT.pptx
75539-Cyber Security Challenges PPT.pptxAsmae Rabhi
 
APNIC Policy Roundup, presented by Sunny Chendi at the 5th ICANN APAC-TWNIC E...
APNIC Policy Roundup, presented by Sunny Chendi at the 5th ICANN APAC-TWNIC E...APNIC Policy Roundup, presented by Sunny Chendi at the 5th ICANN APAC-TWNIC E...
APNIC Policy Roundup, presented by Sunny Chendi at the 5th ICANN APAC-TWNIC E...APNIC
 
Nagercoil Escorts Service Girl ^ 9332606886, WhatsApp Anytime Nagercoil
Nagercoil Escorts Service Girl ^ 9332606886, WhatsApp Anytime NagercoilNagercoil Escorts Service Girl ^ 9332606886, WhatsApp Anytime Nagercoil
Nagercoil Escorts Service Girl ^ 9332606886, WhatsApp Anytime Nagercoilmeghakumariji156
 
在线制作约克大学毕业证(yu毕业证)在读证明认证可查
在线制作约克大学毕业证(yu毕业证)在读证明认证可查在线制作约克大学毕业证(yu毕业证)在读证明认证可查
在线制作约克大学毕业证(yu毕业证)在读证明认证可查ydyuyu
 
Russian Call girls in Abu Dhabi 0508644382 Abu Dhabi Call girls
Russian Call girls in Abu Dhabi 0508644382 Abu Dhabi Call girlsRussian Call girls in Abu Dhabi 0508644382 Abu Dhabi Call girls
Russian Call girls in Abu Dhabi 0508644382 Abu Dhabi Call girlsMonica Sydney
 
Best SEO Services Company in Dallas | Best SEO Agency Dallas
Best SEO Services Company in Dallas | Best SEO Agency DallasBest SEO Services Company in Dallas | Best SEO Agency Dallas
Best SEO Services Company in Dallas | Best SEO Agency DallasDigicorns Technologies
 
一比一原版(Curtin毕业证书)科廷大学毕业证原件一模一样
一比一原版(Curtin毕业证书)科廷大学毕业证原件一模一样一比一原版(Curtin毕业证书)科廷大学毕业证原件一模一样
一比一原版(Curtin毕业证书)科廷大学毕业证原件一模一样ayvbos
 
Meaning of On page SEO & its process in detail.
Meaning of On page SEO & its process in detail.Meaning of On page SEO & its process in detail.
Meaning of On page SEO & its process in detail.krishnachandrapal52
 
20240508 QFM014 Elixir Reading List April 2024.pdf
20240508 QFM014 Elixir Reading List April 2024.pdf20240508 QFM014 Elixir Reading List April 2024.pdf
20240508 QFM014 Elixir Reading List April 2024.pdfMatthew Sinclair
 
一比一原版(Flinders毕业证书)弗林德斯大学毕业证原件一模一样
一比一原版(Flinders毕业证书)弗林德斯大学毕业证原件一模一样一比一原版(Flinders毕业证书)弗林德斯大学毕业证原件一模一样
一比一原版(Flinders毕业证书)弗林德斯大学毕业证原件一模一样ayvbos
 
20240509 QFM015 Engineering Leadership Reading List April 2024.pdf
20240509 QFM015 Engineering Leadership Reading List April 2024.pdf20240509 QFM015 Engineering Leadership Reading List April 2024.pdf
20240509 QFM015 Engineering Leadership Reading List April 2024.pdfMatthew Sinclair
 
APNIC Updates presented by Paul Wilson at ARIN 53
APNIC Updates presented by Paul Wilson at ARIN 53APNIC Updates presented by Paul Wilson at ARIN 53
APNIC Updates presented by Paul Wilson at ARIN 53APNIC
 
pdfcoffee.com_business-ethics-q3m7-pdf-free.pdf
pdfcoffee.com_business-ethics-q3m7-pdf-free.pdfpdfcoffee.com_business-ethics-q3m7-pdf-free.pdf
pdfcoffee.com_business-ethics-q3m7-pdf-free.pdfJOHNBEBONYAP1
 
Vip Firozabad Phone 8250092165 Escorts Service At 6k To 30k Along With Ac Room
Vip Firozabad Phone 8250092165 Escorts Service At 6k To 30k Along With Ac RoomVip Firozabad Phone 8250092165 Escorts Service At 6k To 30k Along With Ac Room
Vip Firozabad Phone 8250092165 Escorts Service At 6k To 30k Along With Ac Roommeghakumariji156
 

Recently uploaded (20)

Story Board.pptxrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr
Story Board.pptxrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrStory Board.pptxrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr
Story Board.pptxrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr
 
原版制作美国爱荷华大学毕业证(iowa毕业证书)学位证网上存档可查
原版制作美国爱荷华大学毕业证(iowa毕业证书)学位证网上存档可查原版制作美国爱荷华大学毕业证(iowa毕业证书)学位证网上存档可查
原版制作美国爱荷华大学毕业证(iowa毕业证书)学位证网上存档可查
 
哪里办理美国迈阿密大学毕业证(本硕)umiami在读证明存档可查
哪里办理美国迈阿密大学毕业证(本硕)umiami在读证明存档可查哪里办理美国迈阿密大学毕业证(本硕)umiami在读证明存档可查
哪里办理美国迈阿密大学毕业证(本硕)umiami在读证明存档可查
 
PowerDirector Explination Process...pptx
PowerDirector Explination Process...pptxPowerDirector Explination Process...pptx
PowerDirector Explination Process...pptx
 
Power point inglese - educazione civica di Nuria Iuzzolino
Power point inglese - educazione civica di Nuria IuzzolinoPower point inglese - educazione civica di Nuria Iuzzolino
Power point inglese - educazione civica di Nuria Iuzzolino
 
"Boost Your Digital Presence: Partner with a Leading SEO Agency"
"Boost Your Digital Presence: Partner with a Leading SEO Agency""Boost Your Digital Presence: Partner with a Leading SEO Agency"
"Boost Your Digital Presence: Partner with a Leading SEO Agency"
 
75539-Cyber Security Challenges PPT.pptx
75539-Cyber Security Challenges PPT.pptx75539-Cyber Security Challenges PPT.pptx
75539-Cyber Security Challenges PPT.pptx
 
APNIC Policy Roundup, presented by Sunny Chendi at the 5th ICANN APAC-TWNIC E...
APNIC Policy Roundup, presented by Sunny Chendi at the 5th ICANN APAC-TWNIC E...APNIC Policy Roundup, presented by Sunny Chendi at the 5th ICANN APAC-TWNIC E...
APNIC Policy Roundup, presented by Sunny Chendi at the 5th ICANN APAC-TWNIC E...
 
Nagercoil Escorts Service Girl ^ 9332606886, WhatsApp Anytime Nagercoil
Nagercoil Escorts Service Girl ^ 9332606886, WhatsApp Anytime NagercoilNagercoil Escorts Service Girl ^ 9332606886, WhatsApp Anytime Nagercoil
Nagercoil Escorts Service Girl ^ 9332606886, WhatsApp Anytime Nagercoil
 
在线制作约克大学毕业证(yu毕业证)在读证明认证可查
在线制作约克大学毕业证(yu毕业证)在读证明认证可查在线制作约克大学毕业证(yu毕业证)在读证明认证可查
在线制作约克大学毕业证(yu毕业证)在读证明认证可查
 
Russian Call girls in Abu Dhabi 0508644382 Abu Dhabi Call girls
Russian Call girls in Abu Dhabi 0508644382 Abu Dhabi Call girlsRussian Call girls in Abu Dhabi 0508644382 Abu Dhabi Call girls
Russian Call girls in Abu Dhabi 0508644382 Abu Dhabi Call girls
 
Best SEO Services Company in Dallas | Best SEO Agency Dallas
Best SEO Services Company in Dallas | Best SEO Agency DallasBest SEO Services Company in Dallas | Best SEO Agency Dallas
Best SEO Services Company in Dallas | Best SEO Agency Dallas
 
一比一原版(Curtin毕业证书)科廷大学毕业证原件一模一样
一比一原版(Curtin毕业证书)科廷大学毕业证原件一模一样一比一原版(Curtin毕业证书)科廷大学毕业证原件一模一样
一比一原版(Curtin毕业证书)科廷大学毕业证原件一模一样
 
Meaning of On page SEO & its process in detail.
Meaning of On page SEO & its process in detail.Meaning of On page SEO & its process in detail.
Meaning of On page SEO & its process in detail.
 
20240508 QFM014 Elixir Reading List April 2024.pdf
20240508 QFM014 Elixir Reading List April 2024.pdf20240508 QFM014 Elixir Reading List April 2024.pdf
20240508 QFM014 Elixir Reading List April 2024.pdf
 
一比一原版(Flinders毕业证书)弗林德斯大学毕业证原件一模一样
一比一原版(Flinders毕业证书)弗林德斯大学毕业证原件一模一样一比一原版(Flinders毕业证书)弗林德斯大学毕业证原件一模一样
一比一原版(Flinders毕业证书)弗林德斯大学毕业证原件一模一样
 
20240509 QFM015 Engineering Leadership Reading List April 2024.pdf
20240509 QFM015 Engineering Leadership Reading List April 2024.pdf20240509 QFM015 Engineering Leadership Reading List April 2024.pdf
20240509 QFM015 Engineering Leadership Reading List April 2024.pdf
 
APNIC Updates presented by Paul Wilson at ARIN 53
APNIC Updates presented by Paul Wilson at ARIN 53APNIC Updates presented by Paul Wilson at ARIN 53
APNIC Updates presented by Paul Wilson at ARIN 53
 
pdfcoffee.com_business-ethics-q3m7-pdf-free.pdf
pdfcoffee.com_business-ethics-q3m7-pdf-free.pdfpdfcoffee.com_business-ethics-q3m7-pdf-free.pdf
pdfcoffee.com_business-ethics-q3m7-pdf-free.pdf
 
Vip Firozabad Phone 8250092165 Escorts Service At 6k To 30k Along With Ac Room
Vip Firozabad Phone 8250092165 Escorts Service At 6k To 30k Along With Ac RoomVip Firozabad Phone 8250092165 Escorts Service At 6k To 30k Along With Ac Room
Vip Firozabad Phone 8250092165 Escorts Service At 6k To 30k Along With Ac Room
 

Socket.io (part 1)

  • 2. Hello! I am Andrea Tarquini I am a full stack developer (mainly working with MEAN stack) and an IT (security) geek and fan. Follow me at: @h4t0n h4t0n Andrea Tarquini blog.h4t0n.com
  • 3. socket.io an unconventional tutorial -- PART 1 We’ll see a socket.io simple introduction: 1. how it works (hacker style) ○ taking a look at what happens within the browser 2. get started with socket.io ○ some references to good starting points for beginners (but not followed by this tutorial) 3. how it works (engineer style) ○ writing some application examples from the official documentation
  • 4. Before starting… What is Socket.io ? ■ Essentially a fast real time engine ■ It enables real-time bidirectional event- based communication ■ It works on every platform, browser, device. ■ Mainly used for ○ Instant messaging and chat ○ Document collaboration ○ Binary streaming (image/video/audio… ) from version 1.0
  • 5. 1. How it works (hacker style) Let’s start taking a look at what happens within the browser
  • 6. So let’s open socket.io with the Chrome Dev Console
  • 7. Let’s type /socket.io on the network filter
  • 8. There are two socket.io realtime connections One for slack
  • 9. There are two socket.io realtime connections One for tweets
  • 10. There are some strange requests…. Both the socket.io connections ■ start with xhr-polling (long polling) ■ then switch to websocket transport (if supported) [more info here]
  • 11. Let’s see the web socket data for tweets.. We have some control data and we can also identify the tweets seen in the home page
  • 12. Let’s play with the chat to understand exchanged data...
  • 13. I talked a bit in the chat…
  • 14. … but let’s see what happened using the console A lot of data → control, messages and events
  • 15. What have we learned from the client (browser)? Events The client listen to events notifications and also emits events. In the chat example, events are: ■ client → server ○ typing ○ stop typing ○ new message ■ server → client ○ typing ○ user left ○ new message Messages Each event (listened or emitted) can have an associated message that is the most important content: ■ strings ■ objects / arrays ■ but also (images, audio,...) ○ Buffers ○ Blobs ○ ArrayBuffers ○ Files
  • 16. If you followed me, you have understood events and messages without reading any line of code or documentation. But if you want to play more with the browser I suggest to take a look at the source code and to use the console with localStorage.debug=”socket.io-client:*” to see debug messages (NB: reload the page)
  • 17. That’s all ? Namespaces Can be used to assign different endpoints (paths) to sockets (default is root / ) It is often used to separate concerns within an application. For example: ■ notification namespace ■ chat namespace Room Inside a namespace (also the root) you can define channels that a socket can join or leave. For example ■ a channel for a restricted chat or team !!!NO!!! The Server has its roles, it can be used to group sockets in namespaces and rooms We don’t see here. We’ll see both in PART 2 !!!!
  • 18. 2. Get Started with socket.io Let’s start with the chat application at socket.io/get-started/chat/
  • 19. The “Hello Word” for Socket.IO !!!! The socket.io chat application is recommended for beginners to Socket.IO or Node.js Follow the tutorial at socket.io/get-started/chat could be very useful for all and it is highly recommended. You can get the full chat example code also on Github: github.com/rauchg/chat-example ATTENTION!!!!! In the following slides we won’t follow the chat application, we’ll work with the documentation.
  • 20. 3. How it works (engineer style) Let’s follow the official socket.io documentation at socket.io/docs/
  • 21. Get the sample code from documentation... You can write your own app with the code available at socket.io/docs or you can get and run the code from socket.io-sample github repository, which contains a list of samples ready to be executed. express-sample1 contains the simplest example you can find on socket.io/docs
  • 22. … code from express-sample1: The Server // express-sample1/server.js var app = require('express')(); var server = require('http').Server(app); var io = require('socket.io')(server); server.listen(8080, function () { var port = server.address().port; console.log('Example app listening on port', port); }); app.get('/', function (req, res) { res.sendFile(__dirname + '/index.html'); }); io.on('connection', function (socket) { socket.emit('news', { hello: 'world' }); socket.on('my other event', function (data) { console.log(data); }); }); Require dependencies and use socket.io with the same express Server Both express and socket.io listen connection on port 8080 (default host is 0.0.0.0) Express is used to easily serve the index page When a client connects, we have a socket instance that can be used to listen/emit event messages: ● the server emit a message (hello world object) on the “news” event (only to the just connected socket) ● the server listen to messages coming from the “my other event” event
  • 23. … code from express-sample1: The index (html page) <!-- index.html --> <script src="/socket.io/socket.io.js"></script> <script> var socket = io.connect('http://localhost:8080'); socket.on('news', function (data) { console.log(data); socket.emit('my other event', { my: 'data' }); }); </script> GET the library from the server (it is automatically served by socket.io) Connect to socket.io and get a socket to use for the event based communication When the client connects, we have a socket instance that can be used to listen/emit event messages: ● the client listen to messages coming from the “news” event ● once one is received the client emit a message (my data object) to “my other event” event
  • 24. … code from express-sample1: run the sample DOWNLOAD THE SAMPLES AND INSTALL NODE DEPENDENCIES $ git clone git@github.com:h4t0n/socket.io-sample.git $ cd socket.io-sample # install package.json dependencies # including socket.io,express,... $ npm install RUN EXPRESS-SAMPLE1 $ node express-sample1/server.js ● now open your browser at http://127.0.0.1:8080 ● take a look at browser and server console
  • 25. … code from express-sample1: another type of client // client.js var io = require('socket.io-client'); var socket = io.connect('http://localhost: 8080'); socket.on('news', function (data) { console.log(data); socket.emit('my other event', { my: 'data' }); }); ATTENTION!!!!! To interact with a socket.io server we don’t need a browser at all. We can use a standalone Node.js script client. We have to use the socket.io-client module (already installed in the previous slide command $ npm install ) TODO!! Run the client more times from several terminal and take a look at the server console.
  • 26. From the example we have seen how to: ■ create a socket.io server ■ connect to the server by using a browser or a standalone node app (script) ■ listen and emit event messages ○ from a single client to the server and vice versa SO… VERY SIMPLE AND BASIC CONCEPTS... .. .BUT THERE IS MUCH MORE !!!!!!!
  • 27. Socket.io allows also to: ■ emit messages to all the connected clients ■ broadcast messages ○ sending message to everyone else except the socket that start the communication (that emit an event) ■ send volatile messages ■ send and get acknowledgments ■ listen to other default events ○ such as the disconnect one ■ be used just as a cross browser websocket ○ without events or other socket.io additions The socket.io/docs overview treats these concepts...
  • 28. express-sample2 is a simple web app that easily shows other most used features: ■ broadcast messages ■ emit messages to all connected clients ■ listen to disconnect event ■ emit messages without using socket.io events (just as a cross browser websocket) …or you can take a look at express-sample2 from socket. io-sample repository !!!! SO PLAY WITH EXPRESS-SAMPLE2 !!!
  • 29. ■ namespaces ■ rooms ■ middlewares ■ etcetera… WE’LL SEE MORE FEATURES AND EXAMPLES IN THE TUTORIAL PART 2
  • 30. Thanks! Any questions? You can find me at: @h4t0n h4t0n Andrea Tarquini blog.h4t0n.com