SlideShare a Scribd company logo
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
Ad

More Related Content

What's hot (20)

Going realtime with Socket.IO
Going realtime with Socket.IOGoing realtime with Socket.IO
Going realtime with Socket.IO
Christian Joudrey
 
「なにをどこまでやれば?」OWASP SAMMが導く開発セキュリティ強化戦略
「なにをどこまでやれば?」OWASP SAMMが導く開発セキュリティ強化戦略「なにをどこまでやれば?」OWASP SAMMが導く開発セキュリティ強化戦略
「なにをどこまでやれば?」OWASP SAMMが導く開発セキュリティ強化戦略
Riotaro OKADA
 
オンプレ回帰も簡単実現!自由自在なデータベース運用とは
オンプレ回帰も簡単実現!自由自在なデータベース運用とはオンプレ回帰も簡単実現!自由自在なデータベース運用とは
オンプレ回帰も簡単実現!自由自在なデータベース運用とは
株式会社クライム
 
MongoDBの脆弱性診断 - smarttechgeeks
MongoDBの脆弱性診断 - smarttechgeeksMongoDBの脆弱性診断 - smarttechgeeks
MongoDBの脆弱性診断 - smarttechgeeks
tobaru_yuta
 
AWSインスタンス設定手順書
AWSインスタンス設定手順書AWSインスタンス設定手順書
AWSインスタンス設定手順書
iret, Inc.
 
Oracle Cloud Infrastructure:2022年9月度サービス・アップデート
Oracle Cloud Infrastructure:2022年9月度サービス・アップデートOracle Cloud Infrastructure:2022年9月度サービス・アップデート
Oracle Cloud Infrastructure:2022年9月度サービス・アップデート
オラクルエンジニア通信
 
Aws amplify studioが変えるフロントエンド開発の未来とは v2
Aws amplify studioが変えるフロントエンド開発の未来とは v2Aws amplify studioが変えるフロントエンド開発の未来とは v2
Aws amplify studioが変えるフロントエンド開発の未来とは v2
Koitabashi Yoshitaka
 
私はここでつまづいた! Oracle database 11g から 12cへのアップグレードと Oracle Database 12c の新機能@201...
私はここでつまづいた! Oracle database 11g から 12cへのアップグレードと Oracle Database 12c の新機能@201...私はここでつまづいた! Oracle database 11g から 12cへのアップグレードと Oracle Database 12c の新機能@201...
私はここでつまづいた! Oracle database 11g から 12cへのアップグレードと Oracle Database 12c の新機能@201...
yoshimotot
 
【Oracle Cloud ウェビナー】WebLogic Serverのご紹介
【Oracle Cloud ウェビナー】WebLogic Serverのご紹介【Oracle Cloud ウェビナー】WebLogic Serverのご紹介
【Oracle Cloud ウェビナー】WebLogic Serverのご紹介
オラクルエンジニア通信
 
Lightweight Keycloak
Lightweight KeycloakLightweight Keycloak
Lightweight Keycloak
Hiroyuki Wada
 
Breaking Bad CSP
Breaking Bad CSPBreaking Bad CSP
Breaking Bad CSP
Lukas Weichselbaum
 
The Security Code Review Guide
The Security Code Review GuideThe Security Code Review Guide
The Security Code Review Guide
Nicola Pietroluongo
 
SQLインジェクション再考
SQLインジェクション再考SQLインジェクション再考
SQLインジェクション再考
Hiroshi Tokumaru
 
Real Time Communication using Node.js and Socket.io
Real Time Communication using Node.js and Socket.ioReal Time Communication using Node.js and Socket.io
Real Time Communication using Node.js and Socket.io
Mindfire Solutions
 
脆弱性検査ツールってどうよ
脆弱性検査ツールってどうよ脆弱性検査ツールってどうよ
脆弱性検査ツールってどうよ
Masakazu Ikeda
 
OpenID Connect入門
OpenID Connect入門OpenID Connect入門
OpenID Connect入門
土岐 孝平
 
Local File Inclusion to Remote Code Execution
Local File Inclusion to Remote Code ExecutionLocal File Inclusion to Remote Code Execution
Local File Inclusion to Remote Code Execution
n|u - The Open Security Community
 
Kafka on Kubernetes: Keeping It Simple (Nikki Thean, Etsy) Kafka Summit SF 2019
Kafka on Kubernetes: Keeping It Simple (Nikki Thean, Etsy) Kafka Summit SF 2019Kafka on Kubernetes: Keeping It Simple (Nikki Thean, Etsy) Kafka Summit SF 2019
Kafka on Kubernetes: Keeping It Simple (Nikki Thean, Etsy) Kafka Summit SF 2019
confluent
 
WebブラウザでC#実行 WebAssemblyの技術
WebブラウザでC#実行 WebAssemblyの技術WebブラウザでC#実行 WebAssemblyの技術
WebブラウザでC#実行 WebAssemblyの技術
Sho Okada
 
Going realtime with Socket.IO
Going realtime with Socket.IOGoing realtime with Socket.IO
Going realtime with Socket.IO
Christian Joudrey
 
「なにをどこまでやれば?」OWASP SAMMが導く開発セキュリティ強化戦略
「なにをどこまでやれば?」OWASP SAMMが導く開発セキュリティ強化戦略「なにをどこまでやれば?」OWASP SAMMが導く開発セキュリティ強化戦略
「なにをどこまでやれば?」OWASP SAMMが導く開発セキュリティ強化戦略
Riotaro OKADA
 
オンプレ回帰も簡単実現!自由自在なデータベース運用とは
オンプレ回帰も簡単実現!自由自在なデータベース運用とはオンプレ回帰も簡単実現!自由自在なデータベース運用とは
オンプレ回帰も簡単実現!自由自在なデータベース運用とは
株式会社クライム
 
MongoDBの脆弱性診断 - smarttechgeeks
MongoDBの脆弱性診断 - smarttechgeeksMongoDBの脆弱性診断 - smarttechgeeks
MongoDBの脆弱性診断 - smarttechgeeks
tobaru_yuta
 
AWSインスタンス設定手順書
AWSインスタンス設定手順書AWSインスタンス設定手順書
AWSインスタンス設定手順書
iret, Inc.
 
Oracle Cloud Infrastructure:2022年9月度サービス・アップデート
Oracle Cloud Infrastructure:2022年9月度サービス・アップデートOracle Cloud Infrastructure:2022年9月度サービス・アップデート
Oracle Cloud Infrastructure:2022年9月度サービス・アップデート
オラクルエンジニア通信
 
Aws amplify studioが変えるフロントエンド開発の未来とは v2
Aws amplify studioが変えるフロントエンド開発の未来とは v2Aws amplify studioが変えるフロントエンド開発の未来とは v2
Aws amplify studioが変えるフロントエンド開発の未来とは v2
Koitabashi Yoshitaka
 
私はここでつまづいた! Oracle database 11g から 12cへのアップグレードと Oracle Database 12c の新機能@201...
私はここでつまづいた! Oracle database 11g から 12cへのアップグレードと Oracle Database 12c の新機能@201...私はここでつまづいた! Oracle database 11g から 12cへのアップグレードと Oracle Database 12c の新機能@201...
私はここでつまづいた! Oracle database 11g から 12cへのアップグレードと Oracle Database 12c の新機能@201...
yoshimotot
 
【Oracle Cloud ウェビナー】WebLogic Serverのご紹介
【Oracle Cloud ウェビナー】WebLogic Serverのご紹介【Oracle Cloud ウェビナー】WebLogic Serverのご紹介
【Oracle Cloud ウェビナー】WebLogic Serverのご紹介
オラクルエンジニア通信
 
Lightweight Keycloak
Lightweight KeycloakLightweight Keycloak
Lightweight Keycloak
Hiroyuki Wada
 
SQLインジェクション再考
SQLインジェクション再考SQLインジェクション再考
SQLインジェクション再考
Hiroshi Tokumaru
 
Real Time Communication using Node.js and Socket.io
Real Time Communication using Node.js and Socket.ioReal Time Communication using Node.js and Socket.io
Real Time Communication using Node.js and Socket.io
Mindfire Solutions
 
脆弱性検査ツールってどうよ
脆弱性検査ツールってどうよ脆弱性検査ツールってどうよ
脆弱性検査ツールってどうよ
Masakazu Ikeda
 
OpenID Connect入門
OpenID Connect入門OpenID Connect入門
OpenID Connect入門
土岐 孝平
 
Kafka on Kubernetes: Keeping It Simple (Nikki Thean, Etsy) Kafka Summit SF 2019
Kafka on Kubernetes: Keeping It Simple (Nikki Thean, Etsy) Kafka Summit SF 2019Kafka on Kubernetes: Keeping It Simple (Nikki Thean, Etsy) Kafka Summit SF 2019
Kafka on Kubernetes: Keeping It Simple (Nikki Thean, Etsy) Kafka Summit SF 2019
confluent
 
WebブラウザでC#実行 WebAssemblyの技術
WebブラウザでC#実行 WebAssemblyの技術WebブラウザでC#実行 WebAssemblyの技術
WebブラウザでC#実行 WebAssemblyの技術
Sho Okada
 

Viewers also liked (20)

Socket.IO
Socket.IOSocket.IO
Socket.IO
Arnout Kazemier
 
Going real time with Socket.io
Going real time with Socket.ioGoing real time with Socket.io
Going real time with Socket.io
Arnout 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 Redis
York 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 intro
eddify
 
Socket io - JSZurich
Socket io - JSZurichSocket io - JSZurich
Socket io - JSZurich
streunerlein
 
Node worshop Realtime - Socket.io
Node worshop Realtime - Socket.ioNode worshop Realtime - Socket.io
Node worshop Realtime - Socket.io
Caesar 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 SocketIO
Hüseyin BABAL
 
Better d3 charts with tdd
Better d3 charts with tddBetter d3 charts with tdd
Better d3 charts with tdd
Marcos Iglesias
 
Data visualization
Data visualizationData visualization
Data visualization
sagalabo
 
tea
teatea
tea
sagalabo
 
Transforming WebSockets
Transforming WebSocketsTransforming WebSockets
Transforming WebSockets
Arnout Kazemier
 
Building your First MEAN App
Building your First MEAN AppBuilding your First MEAN App
Building your First MEAN App
MongoDB
 
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
Thomas 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 2014
Stéphane ESCANDELL
 
Web socket with php v2
Web socket with php v2Web socket with php v2
Web socket with php v2
Leonardo Rifeli
 
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
Vorakamol Choonhasakulchok
 
Socket Programming
Socket ProgrammingSocket Programming
Socket Programming
VisualBee.com
 
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
Tomomi 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.js
async_io
 
Socket.io
Socket.ioSocket.io
Socket.io
Timothy Fitz
 
Going real time with Socket.io
Going real time with Socket.ioGoing real time with Socket.io
Going real time with Socket.io
Arnout 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 Redis
York 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 intro
eddify
 
Socket io - JSZurich
Socket io - JSZurichSocket io - JSZurich
Socket io - JSZurich
streunerlein
 
Node worshop Realtime - Socket.io
Node worshop Realtime - Socket.ioNode worshop Realtime - Socket.io
Node worshop Realtime - Socket.io
Caesar 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 SocketIO
Hüseyin BABAL
 
Better d3 charts with tdd
Better d3 charts with tddBetter d3 charts with tdd
Better d3 charts with tdd
Marcos Iglesias
 
Data visualization
Data visualizationData visualization
Data visualization
sagalabo
 
Building your First MEAN App
Building your First MEAN AppBuilding your First MEAN App
Building your First MEAN App
MongoDB
 
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
Thomas 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 2014
Sté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 Application
Vorakamol 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 JSON
Tomomi 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.js
async_io
 
Ad

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

Tornado Web Server Internals
Tornado Web Server InternalsTornado Web Server Internals
Tornado Web Server Internals
Praveen Gollakota
 
Book
BookBook
Book
luis_lmro
 
Python networking
Python networkingPython networking
Python networking
Smt. Indira Gandhi College of Engineering, Navi Mumbai, Mumbai
 
A.java
A.javaA.java
A.java
JahnaviBhagat
 
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 Ruby
Mike 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 backend
David Padbury
 
TCP Sockets Tutor maXbox starter26
TCP Sockets Tutor maXbox starter26TCP Sockets Tutor maXbox starter26
TCP Sockets Tutor maXbox starter26
Max 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 talk
Aarti Parikh
 
Java sockets
Java socketsJava sockets
Java sockets
Stephen Pradeep
 
Ransomware for fun and non-profit
Ransomware for fun and non-profitRansomware for fun and non-profit
Ransomware for fun and non-profit
Youness Zougar
 
Node.js essentials
 Node.js essentials Node.js essentials
Node.js essentials
Bedis ElAchèche
 
Proposal
ProposalProposal
Proposal
Constantine Priemski
 
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
soft-shake.ch
 
Node.js for Rubists
Node.js for RubistsNode.js for Rubists
Node.js for Rubists
Sagiv 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.io
Katy Slemon
 
PPT-1_19BCS1566.pptx presentation education
PPT-1_19BCS1566.pptx presentation educationPPT-1_19BCS1566.pptx presentation education
PPT-1_19BCS1566.pptx presentation education
arajo4688
 
Java Networking
Java NetworkingJava Networking
Java Networking
Sunil OS
 
Python, do you even async?
Python, do you even async?Python, do you even async?
Python, do you even async?
Saúl Ibarra Corretgé
 
Tornado Web Server Internals
Tornado Web Server InternalsTornado Web Server Internals
Tornado Web Server Internals
Praveen 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 Ruby
Mike 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 backend
David Padbury
 
TCP Sockets Tutor maXbox starter26
TCP Sockets Tutor maXbox starter26TCP Sockets Tutor maXbox starter26
TCP Sockets Tutor maXbox starter26
Max 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 talk
Aarti Parikh
 
Ransomware for fun and non-profit
Ransomware for fun and non-profitRansomware for fun and non-profit
Ransomware for fun and non-profit
Youness 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.js
soft-shake.ch
 
Node.js for Rubists
Node.js for RubistsNode.js for Rubists
Node.js for Rubists
Sagiv 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.io
Katy Slemon
 
PPT-1_19BCS1566.pptx presentation education
PPT-1_19BCS1566.pptx presentation educationPPT-1_19BCS1566.pptx presentation education
PPT-1_19BCS1566.pptx presentation education
arajo4688
 
Java Networking
Java NetworkingJava Networking
Java Networking
Sunil OS
 
Ad

Recently uploaded (19)

White and Red Clean Car Business Pitch Presentation.pptx
White and Red Clean Car Business Pitch Presentation.pptxWhite and Red Clean Car Business Pitch Presentation.pptx
White and Red Clean Car Business Pitch Presentation.pptx
canumatown
 
project_based_laaaaaaaaaaearning,kelompok 10.pptx
project_based_laaaaaaaaaaearning,kelompok 10.pptxproject_based_laaaaaaaaaaearning,kelompok 10.pptx
project_based_laaaaaaaaaaearning,kelompok 10.pptx
redzuriel13
 
Reliable Vancouver Web Hosting with Local Servers & 24/7 Support
Reliable Vancouver Web Hosting with Local Servers & 24/7 SupportReliable Vancouver Web Hosting with Local Servers & 24/7 Support
Reliable Vancouver Web Hosting with Local Servers & 24/7 Support
steve198109
 
Determining Glass is mechanical textile
Determining  Glass is mechanical textileDetermining  Glass is mechanical textile
Determining Glass is mechanical textile
Azizul Hakim
 
Top Vancouver Green Business Ideas for 2025 Powered by 4GoodHosting
Top Vancouver Green Business Ideas for 2025 Powered by 4GoodHostingTop Vancouver Green Business Ideas for 2025 Powered by 4GoodHosting
Top Vancouver Green Business Ideas for 2025 Powered by 4GoodHosting
steve198109
 
highend-srxseries-services-gateways-customer-presentation.pptx
highend-srxseries-services-gateways-customer-presentation.pptxhighend-srxseries-services-gateways-customer-presentation.pptx
highend-srxseries-services-gateways-customer-presentation.pptx
elhadjcheikhdiop
 
5-Proses-proses Akuisisi Citra Digital.pptx
5-Proses-proses Akuisisi Citra Digital.pptx5-Proses-proses Akuisisi Citra Digital.pptx
5-Proses-proses Akuisisi Citra Digital.pptx
andani26
 
DNS Resolvers and Nameservers (in New Zealand)
DNS Resolvers and Nameservers (in New Zealand)DNS Resolvers and Nameservers (in New Zealand)
DNS Resolvers and Nameservers (in New Zealand)
APNIC
 
Perguntas dos animais - Slides ilustrados de múltipla escolha
Perguntas dos animais - Slides ilustrados de múltipla escolhaPerguntas dos animais - Slides ilustrados de múltipla escolha
Perguntas dos animais - Slides ilustrados de múltipla escolha
socaslev
 
Smart Mobile App Pitch Deck丨AI Travel App Presentation Template
Smart Mobile App Pitch Deck丨AI Travel App Presentation TemplateSmart Mobile App Pitch Deck丨AI Travel App Presentation Template
Smart Mobile App Pitch Deck丨AI Travel App Presentation Template
yojeari421237
 
Understanding the Tor Network and Exploring the Deep Web
Understanding the Tor Network and Exploring the Deep WebUnderstanding the Tor Network and Exploring the Deep Web
Understanding the Tor Network and Exploring the Deep Web
nabilajabin35
 
IT Services Workflow From Request to Resolution
IT Services Workflow From Request to ResolutionIT Services Workflow From Request to Resolution
IT Services Workflow From Request to Resolution
mzmziiskd
 
Computers Networks Computers Networks Computers Networks
Computers Networks Computers Networks Computers NetworksComputers Networks Computers Networks Computers Networks
Computers Networks Computers Networks Computers Networks
Tito208863
 
APNIC -Policy Development Process, presented at Local APIGA Taiwan 2025
APNIC -Policy Development Process, presented at Local APIGA Taiwan 2025APNIC -Policy Development Process, presented at Local APIGA Taiwan 2025
APNIC -Policy Development Process, presented at Local APIGA Taiwan 2025
APNIC
 
Mobile database for your company telemarketing or sms marketing campaigns. Fr...
Mobile database for your company telemarketing or sms marketing campaigns. Fr...Mobile database for your company telemarketing or sms marketing campaigns. Fr...
Mobile database for your company telemarketing or sms marketing campaigns. Fr...
DataProvider1
 
Best web hosting Vancouver 2025 for you business
Best web hosting Vancouver 2025 for you businessBest web hosting Vancouver 2025 for you business
Best web hosting Vancouver 2025 for you business
steve198109
 
OSI TCP IP Protocol Layers description f
OSI TCP IP Protocol Layers description fOSI TCP IP Protocol Layers description f
OSI TCP IP Protocol Layers description f
cbr49917
 
APNIC Update, presented at NZNOG 2025 by Terry Sweetser
APNIC Update, presented at NZNOG 2025 by Terry SweetserAPNIC Update, presented at NZNOG 2025 by Terry Sweetser
APNIC Update, presented at NZNOG 2025 by Terry Sweetser
APNIC
 
(Hosting PHising Sites) for Cryptography and network security
(Hosting PHising Sites) for Cryptography and network security(Hosting PHising Sites) for Cryptography and network security
(Hosting PHising Sites) for Cryptography and network security
aluacharya169
 
White and Red Clean Car Business Pitch Presentation.pptx
White and Red Clean Car Business Pitch Presentation.pptxWhite and Red Clean Car Business Pitch Presentation.pptx
White and Red Clean Car Business Pitch Presentation.pptx
canumatown
 
project_based_laaaaaaaaaaearning,kelompok 10.pptx
project_based_laaaaaaaaaaearning,kelompok 10.pptxproject_based_laaaaaaaaaaearning,kelompok 10.pptx
project_based_laaaaaaaaaaearning,kelompok 10.pptx
redzuriel13
 
Reliable Vancouver Web Hosting with Local Servers & 24/7 Support
Reliable Vancouver Web Hosting with Local Servers & 24/7 SupportReliable Vancouver Web Hosting with Local Servers & 24/7 Support
Reliable Vancouver Web Hosting with Local Servers & 24/7 Support
steve198109
 
Determining Glass is mechanical textile
Determining  Glass is mechanical textileDetermining  Glass is mechanical textile
Determining Glass is mechanical textile
Azizul Hakim
 
Top Vancouver Green Business Ideas for 2025 Powered by 4GoodHosting
Top Vancouver Green Business Ideas for 2025 Powered by 4GoodHostingTop Vancouver Green Business Ideas for 2025 Powered by 4GoodHosting
Top Vancouver Green Business Ideas for 2025 Powered by 4GoodHosting
steve198109
 
highend-srxseries-services-gateways-customer-presentation.pptx
highend-srxseries-services-gateways-customer-presentation.pptxhighend-srxseries-services-gateways-customer-presentation.pptx
highend-srxseries-services-gateways-customer-presentation.pptx
elhadjcheikhdiop
 
5-Proses-proses Akuisisi Citra Digital.pptx
5-Proses-proses Akuisisi Citra Digital.pptx5-Proses-proses Akuisisi Citra Digital.pptx
5-Proses-proses Akuisisi Citra Digital.pptx
andani26
 
DNS Resolvers and Nameservers (in New Zealand)
DNS Resolvers and Nameservers (in New Zealand)DNS Resolvers and Nameservers (in New Zealand)
DNS Resolvers and Nameservers (in New Zealand)
APNIC
 
Perguntas dos animais - Slides ilustrados de múltipla escolha
Perguntas dos animais - Slides ilustrados de múltipla escolhaPerguntas dos animais - Slides ilustrados de múltipla escolha
Perguntas dos animais - Slides ilustrados de múltipla escolha
socaslev
 
Smart Mobile App Pitch Deck丨AI Travel App Presentation Template
Smart Mobile App Pitch Deck丨AI Travel App Presentation TemplateSmart Mobile App Pitch Deck丨AI Travel App Presentation Template
Smart Mobile App Pitch Deck丨AI Travel App Presentation Template
yojeari421237
 
Understanding the Tor Network and Exploring the Deep Web
Understanding the Tor Network and Exploring the Deep WebUnderstanding the Tor Network and Exploring the Deep Web
Understanding the Tor Network and Exploring the Deep Web
nabilajabin35
 
IT Services Workflow From Request to Resolution
IT Services Workflow From Request to ResolutionIT Services Workflow From Request to Resolution
IT Services Workflow From Request to Resolution
mzmziiskd
 
Computers Networks Computers Networks Computers Networks
Computers Networks Computers Networks Computers NetworksComputers Networks Computers Networks Computers Networks
Computers Networks Computers Networks Computers Networks
Tito208863
 
APNIC -Policy Development Process, presented at Local APIGA Taiwan 2025
APNIC -Policy Development Process, presented at Local APIGA Taiwan 2025APNIC -Policy Development Process, presented at Local APIGA Taiwan 2025
APNIC -Policy Development Process, presented at Local APIGA Taiwan 2025
APNIC
 
Mobile database for your company telemarketing or sms marketing campaigns. Fr...
Mobile database for your company telemarketing or sms marketing campaigns. Fr...Mobile database for your company telemarketing or sms marketing campaigns. Fr...
Mobile database for your company telemarketing or sms marketing campaigns. Fr...
DataProvider1
 
Best web hosting Vancouver 2025 for you business
Best web hosting Vancouver 2025 for you businessBest web hosting Vancouver 2025 for you business
Best web hosting Vancouver 2025 for you business
steve198109
 
OSI TCP IP Protocol Layers description f
OSI TCP IP Protocol Layers description fOSI TCP IP Protocol Layers description f
OSI TCP IP Protocol Layers description f
cbr49917
 
APNIC Update, presented at NZNOG 2025 by Terry Sweetser
APNIC Update, presented at NZNOG 2025 by Terry SweetserAPNIC Update, presented at NZNOG 2025 by Terry Sweetser
APNIC Update, presented at NZNOG 2025 by Terry Sweetser
APNIC
 
(Hosting PHising Sites) for Cryptography and network security
(Hosting PHising Sites) for Cryptography and network security(Hosting PHising Sites) for Cryptography and network security
(Hosting PHising Sites) for Cryptography and network security
aluacharya169
 

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 [email protected]: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