SlideShare ist ein Scribd-Unternehmen logo
1 von 35
Downloaden Sie, um offline zu lesen
Node.js and
    WebSockets

     Gonzalo Ayuso 2011

          @gonzalo123
http://gonzalo123.wordpress.com
 https://github.com/gonzalo123
Part 1. Node.js
Part 2. WebSockets
Node.js | What's node.js


● JavaScript on the server
● Written by Ryan Dahl
● Based on V8 (Google)

● Asynchronous event-driven model
● Similar in design to:
   ○ Event Machine (Ruby)
   ○ Twisted (Python)
Node.js | Why?

      I/O needs to be done differently
Node.js | Why?

           I/O needs to be done differently
From:
  recordset = db.query("select * from Table");
  render(recordset);
Node.js | Why?

           I/O needs to be done differently



Q: When will you add threads to JavaScript?”
A: over your dead body
                          Brendan Eich (creator of JavaScript)
Node.js | Why?

           I/O needs to be done differently
From:
  recordset = db.query("select * from Table");
  render(recordset);
To:
  db.query("select * from Table", function (recordset) {
      render(recordset)
  });
Node.js | Why?

           I/O needs to be done differently
From:
  recordset = db.query("select * from Table")
  render(recordset)
To:
  db.query("select * from Table", function (recordset) {
      render(recordset)
  });

                         Design Goals

 ● No function should direct perform I/O.
 ● To read info from disk, network, ... there must be a callback
Node.js | Show me the code!

HTTP SERVER
var http = require('http');

http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello Worldn');
}).listen(1337, "127.0.0.1");

console.log('Server running at http://127.0.0.1:1337/');
Node.js | Show me the code!

HTTP SERVER
var http = require('http');
var total = 0;

http.createServer(function (req, res) {
  res.writeHead(200, {
    'Content-Type': 'text/plain'
  });
  res.end('Hi ' + total + 'n');
  tot++;
}).listen(1337, "127.0.0.1");

console.log('Server running at http://127.0.0.1:1337/');
Node.js | Pros and Cons

PROS
 ● Great I/O performance
 ● Just JavaScript. We all know JavaScript
 ● Community
 ● A lot of modules available https://github.
   com/joyent/node/wiki/modules
 ● npm
Node.js | Pros and Cons

PROS
 ● Great I/O performance
 ● Just JavaScript. We all know JavaScript
 ● Community
 ● A lot of modules available https://github.
   com/joyent/node/wiki/modules
 ● npm
CONS
 ● Hosting
 ● We don't really know JavaScript
 ● Modules too young
 ● One thread, one single process for all
 ● Windows support
Part 1. Node.js
Part 2. WebSockets
WebSockets | History

Description of the problem:
 ● Real time communications in Browser
WebSockets | History

Description of the problem:
 ● Real time communications in Browser

Imagine. Let's create simple chat client (5 years ago):

Trivial problem with heavy clients, hard in browsers.
WebSockets | History

COMET (Wikipedia):
Comet is a web application model in which a long-held HTTP request
allows a web server to push data to a browser, without the browser
explicitly requesting it.
WebSockets | History

COMET (Wikipedia):
Comet is a web application model in which a long-held HTTP request
allows a web server to push data to a browser, without the browser
explicitly requesting it.


Problem with COMET:
 ● Servers (keep-alive, MaxClients, ...)
 ● Clients
WebSockets | History

COMET (Wikipedia):
Comet is a web application model in which a long-held HTTP request
allows a web server to push data to a browser, without the browser
explicitly requesting it.


Problem with COMET:
 ● Servers (keep-alive, MaxClients, ...)
 ● Clients
WebSockets | Short Polling / Long
Polling
Short Polling
 ● <meta http-equiv="refresh" content="5">
 ● setInterval and setTimeout
 ● Inneficient
 ● Uses many resources (DB Connection, ...)
WebSockets | Short Polling / Long
Polling
Short Polling
 ● <meta http-equiv="refresh" content="5">
 ● setInterval and setTimeout
 ● Inneficient
 ● Uses many resources (DB Connection, ...)

Long Pooling
 ● Looks like Real Time but it isn't RT
WebSockets | Short Polling / Long
Polling
Short Polling
 ● <meta http-equiv="refresh" content="5">
 ● setInterval and setTimeout
 ● Inneficient
 ● Uses many resources (DB Connection, ...)

Long Pooling
 ● Looks like Real Time but it isn't RT

It works? Yes
It scales? No (Long Polling better but still No)
Is your sysadmin happy? No
WebSockets | Short Polling / Long
Polling
Short Polling
 ● <meta http-equiv="refresh" content="5">
 ● setInterval and setTimeout
 ● Inneficient
 ● Uses many resources (DB Connection, ...)

Long Pooling
 ● Looks like Real Time but it isn't RT

It works? Yes
It scales? No (Long Polling better but still No)
Is your sysadmin happy? No
WebSockets | HTML5

WebSockets
This specification defines an API that enables Web pages to use the
WebSocket protocol for two-way communication with a remote host.
WebSockets | HTML5

WebSockets
This specification defines an API that enables Web pages to use the
WebSocket protocol for two-way communication with a remote host.

That's means:
 ● The solution of the problem with RT at browser side
WebSockets | HTML5

var ws = new WebSocket(url);
ws.onopen = function() {
    // When the connection opens
 };
ws.onmessage = function() {
    // When the server sends data
 };
ws.onclose = function() {
    // When the connection is closed
 };
ws.send('Hi all');
// later...
ws.close();
WebSockets | HTML5




            Cool but ...
WebSockets | HTML5




             Cool but ...
      Not all browsers support it
WebSockets | socket.io

Is there a solution?
WebSockets | socket.io

Is there a solution?

                       http://socket.io/
WebSockets | socket.io

Is there a solution?

                                               http://socket.io/

  Client
<script src="/socket.io/socket.io.js"></script>
<script>
 var socket = io.connect('http://localhost');
 socket.on('news', function (data) {
   console.log(data);
   socket.emit('my other event', { my: 'data' });
 });
</script>
WebSockets | socket.io

Is there a solution?

                                               http://socket.io/

  Client
<script src="/socket.io/socket.io.js"></script>
<script>
 var socket = io.connect('http://localhost');            Server (node.js application)
 socket.on('news', function (data) {
   console.log(data);                                    var io = require('socket.io').listen(80);
   socket.emit('my other event', { my: 'data' });
 });                                                     io.sockets.on('connection', function (socket) {
</script>                                                  socket.emit('news', { hello: 'world' });
                                                           socket.on('my other event', function (data) {
                                                             console.log(data);
                                                           });
                                                         });
WebSockets | socket.io


                       http://socket.io/
Supported transports
 ● WebSocket
 ● Adobe® Flash® Socket
 ● AJAX long polling
 ● AJAX multipart streaming
 ● Forever Iframe
 ● JSONP Polling
WebSockets | socket.io


                       http://socket.io/
Supported transports          Supported browsers
 ● WebSocket                   ● Internet Explorer 5.5+
 ● Adobe® Flash® Socket        ● Safari 3+
 ● AJAX long polling           ● Google Chrome 4+
 ● AJAX multipart streaming    ● Firefox 3+
 ● Forever Iframe              ● Opera 10.61+
 ● JSONP Polling               ● iPhone Safari
                               ● iPad Safari
                               ● Android WebKit
                               ● WebOs WebKit
References


● http://dev.w3.org/html5/websockets/
● https://github.com/joyent/node/wiki/modules
● http://nodejs.org/
● http://socket.io/
● http://en.wikipedia.org/wiki/Push_technology
● http://www.youtube.com/watch?v=jo_B4LTHi3I
● http://gonzalo123.wordpress.
  com/category/technology/node-js/
The End.

    Many thanks
          @gonzalo123
http://gonzalo123.wordpress.com

Weitere ähnliche Inhalte

Was ist angesagt?

Google Chromebook for the Enterprise: Yeah or Meh?
Google Chromebook for the Enterprise: Yeah or Meh?Google Chromebook for the Enterprise: Yeah or Meh?
Google Chromebook for the Enterprise: Yeah or Meh?Ericom Software
 
Kettunen, miaubiz fuzzing at scale and in style
Kettunen, miaubiz   fuzzing at scale and in styleKettunen, miaubiz   fuzzing at scale and in style
Kettunen, miaubiz fuzzing at scale and in styleDefconRussia
 
Introduction to REST API with Node.js
Introduction to REST API with Node.jsIntroduction to REST API with Node.js
Introduction to REST API with Node.jsYoann Gotthilf
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.jsJack Franklin
 
WebSockets Everywhere: the Future Transport Protocol for Everything (Almost)
WebSockets Everywhere: the Future Transport Protocol for Everything (Almost)WebSockets Everywhere: the Future Transport Protocol for Everything (Almost)
WebSockets Everywhere: the Future Transport Protocol for Everything (Almost)Ericom Software
 
My month with Ruby
My month with RubyMy month with Ruby
My month with Rubyalextomovski
 
ECMAScript 6 from an Attacker's Perspective - Breaking Frameworks, Sandboxes,...
ECMAScript 6 from an Attacker's Perspective - Breaking Frameworks, Sandboxes,...ECMAScript 6 from an Attacker's Perspective - Breaking Frameworks, Sandboxes,...
ECMAScript 6 from an Attacker's Perspective - Breaking Frameworks, Sandboxes,...Mario Heiderich
 
Node Js Websocket Js Meetup Slides
Node Js Websocket Js Meetup SlidesNode Js Websocket Js Meetup Slides
Node Js Websocket Js Meetup SlidesMakoto Inoue
 
Fundamental of Node.JS - Internship Presentation - Week7
Fundamental of Node.JS - Internship Presentation - Week7Fundamental of Node.JS - Internship Presentation - Week7
Fundamental of Node.JS - Internship Presentation - Week7Devang Garach
 
Create a RESTful API with NodeJS, Express and MongoDB
Create a RESTful API with NodeJS, Express and MongoDBCreate a RESTful API with NodeJS, Express and MongoDB
Create a RESTful API with NodeJS, Express and MongoDBHengki Sihombing
 
Require js + backbone, bower and grunt
Require js + backbone, bower and gruntRequire js + backbone, bower and grunt
Require js + backbone, bower and gruntJoe Fleming
 

Was ist angesagt? (20)

What is Node.js
What is Node.jsWhat is Node.js
What is Node.js
 
Node js introduction
Node js introductionNode js introduction
Node js introduction
 
Google Chromebook for the Enterprise: Yeah or Meh?
Google Chromebook for the Enterprise: Yeah or Meh?Google Chromebook for the Enterprise: Yeah or Meh?
Google Chromebook for the Enterprise: Yeah or Meh?
 
Kettunen, miaubiz fuzzing at scale and in style
Kettunen, miaubiz   fuzzing at scale and in styleKettunen, miaubiz   fuzzing at scale and in style
Kettunen, miaubiz fuzzing at scale and in style
 
Real time coding with jWebSocket
Real time coding with jWebSocketReal time coding with jWebSocket
Real time coding with jWebSocket
 
Socket.IO
Socket.IOSocket.IO
Socket.IO
 
Introduction to REST API with Node.js
Introduction to REST API with Node.jsIntroduction to REST API with Node.js
Introduction to REST API with Node.js
 
NodeJS
NodeJSNodeJS
NodeJS
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
 
WebSockets Everywhere: the Future Transport Protocol for Everything (Almost)
WebSockets Everywhere: the Future Transport Protocol for Everything (Almost)WebSockets Everywhere: the Future Transport Protocol for Everything (Almost)
WebSockets Everywhere: the Future Transport Protocol for Everything (Almost)
 
(C)NodeJS
(C)NodeJS(C)NodeJS
(C)NodeJS
 
My month with Ruby
My month with RubyMy month with Ruby
My month with Ruby
 
ECMAScript 6 from an Attacker's Perspective - Breaking Frameworks, Sandboxes,...
ECMAScript 6 from an Attacker's Perspective - Breaking Frameworks, Sandboxes,...ECMAScript 6 from an Attacker's Perspective - Breaking Frameworks, Sandboxes,...
ECMAScript 6 from an Attacker's Perspective - Breaking Frameworks, Sandboxes,...
 
Node Js Websocket Js Meetup Slides
Node Js Websocket Js Meetup SlidesNode Js Websocket Js Meetup Slides
Node Js Websocket Js Meetup Slides
 
Fundamental of Node.JS - Internship Presentation - Week7
Fundamental of Node.JS - Internship Presentation - Week7Fundamental of Node.JS - Internship Presentation - Week7
Fundamental of Node.JS - Internship Presentation - Week7
 
Create a RESTful API with NodeJS, Express and MongoDB
Create a RESTful API with NodeJS, Express and MongoDBCreate a RESTful API with NodeJS, Express and MongoDB
Create a RESTful API with NodeJS, Express and MongoDB
 
Require js + backbone, bower and grunt
Require js + backbone, bower and gruntRequire js + backbone, bower and grunt
Require js + backbone, bower and grunt
 
Nodejs presentation
Nodejs presentationNodejs presentation
Nodejs presentation
 
Socket.io
Socket.ioSocket.io
Socket.io
 
NodeJS
NodeJSNodeJS
NodeJS
 

Andere mochten auch

Get Soaked - An In Depth Look At PHP Streams
Get Soaked - An In Depth Look At PHP StreamsGet Soaked - An In Depth Look At PHP Streams
Get Soaked - An In Depth Look At PHP StreamsDavey Shafik
 
Electrify your code with PHP Generators
Electrify your code with PHP GeneratorsElectrify your code with PHP Generators
Electrify your code with PHP GeneratorsMark Baker
 
Techniques d'accélération des pages web
Techniques d'accélération des pages webTechniques d'accélération des pages web
Techniques d'accélération des pages webJean-Pierre Vincent
 
Automation using-phing
Automation using-phingAutomation using-phing
Automation using-phingRajat Pandit
 
The quest for global design principles (SymfonyLive Berlin 2015)
The quest for global design principles (SymfonyLive Berlin 2015)The quest for global design principles (SymfonyLive Berlin 2015)
The quest for global design principles (SymfonyLive Berlin 2015)Matthias Noback
 
Top tips my_sql_performance
Top tips my_sql_performanceTop tips my_sql_performance
Top tips my_sql_performanceafup Paris
 
Why elasticsearch rocks!
Why elasticsearch rocks!Why elasticsearch rocks!
Why elasticsearch rocks!tlrx
 
Understanding Craftsmanship SwanseaCon2015
Understanding Craftsmanship SwanseaCon2015Understanding Craftsmanship SwanseaCon2015
Understanding Craftsmanship SwanseaCon2015Marcello Duarte
 
Si le tdd est mort alors pratiquons une autopsie mix-it 2015
Si le tdd est mort alors pratiquons une autopsie mix-it 2015Si le tdd est mort alors pratiquons une autopsie mix-it 2015
Si le tdd est mort alors pratiquons une autopsie mix-it 2015Bruno Boucard
 
Writing infinite scalability web applications with PHP and PostgreSQL
Writing infinite scalability web applications with PHP and PostgreSQLWriting infinite scalability web applications with PHP and PostgreSQL
Writing infinite scalability web applications with PHP and PostgreSQLGabriele Bartolini
 
L'ABC du BDD (Behavior Driven Development)
L'ABC du BDD (Behavior Driven Development)L'ABC du BDD (Behavior Driven Development)
L'ABC du BDD (Behavior Driven Development)Arnauld Loyer
 
TDD with PhpSpec - Lone Star PHP 2016
TDD with PhpSpec - Lone Star PHP 2016TDD with PhpSpec - Lone Star PHP 2016
TDD with PhpSpec - Lone Star PHP 2016CiaranMcNulty
 
Performance serveur et apache
Performance serveur et apachePerformance serveur et apache
Performance serveur et apacheafup Paris
 
The Wonderful World of Symfony Components
The Wonderful World of Symfony ComponentsThe Wonderful World of Symfony Components
The Wonderful World of Symfony ComponentsRyan Weaver
 

Andere mochten auch (20)

Get Soaked - An In Depth Look At PHP Streams
Get Soaked - An In Depth Look At PHP StreamsGet Soaked - An In Depth Look At PHP Streams
Get Soaked - An In Depth Look At PHP Streams
 
Electrify your code with PHP Generators
Electrify your code with PHP GeneratorsElectrify your code with PHP Generators
Electrify your code with PHP Generators
 
Techniques d'accélération des pages web
Techniques d'accélération des pages webTechniques d'accélération des pages web
Techniques d'accélération des pages web
 
Elastic Searching With PHP
Elastic Searching With PHPElastic Searching With PHP
Elastic Searching With PHP
 
Diving deep into twig
Diving deep into twigDiving deep into twig
Diving deep into twig
 
PHP5.5 is Here
PHP5.5 is HerePHP5.5 is Here
PHP5.5 is Here
 
Automation using-phing
Automation using-phingAutomation using-phing
Automation using-phing
 
The quest for global design principles (SymfonyLive Berlin 2015)
The quest for global design principles (SymfonyLive Berlin 2015)The quest for global design principles (SymfonyLive Berlin 2015)
The quest for global design principles (SymfonyLive Berlin 2015)
 
Top tips my_sql_performance
Top tips my_sql_performanceTop tips my_sql_performance
Top tips my_sql_performance
 
Mocking Demystified
Mocking DemystifiedMocking Demystified
Mocking Demystified
 
Why elasticsearch rocks!
Why elasticsearch rocks!Why elasticsearch rocks!
Why elasticsearch rocks!
 
Understanding Craftsmanship SwanseaCon2015
Understanding Craftsmanship SwanseaCon2015Understanding Craftsmanship SwanseaCon2015
Understanding Craftsmanship SwanseaCon2015
 
Si le tdd est mort alors pratiquons une autopsie mix-it 2015
Si le tdd est mort alors pratiquons une autopsie mix-it 2015Si le tdd est mort alors pratiquons une autopsie mix-it 2015
Si le tdd est mort alors pratiquons une autopsie mix-it 2015
 
Writing infinite scalability web applications with PHP and PostgreSQL
Writing infinite scalability web applications with PHP and PostgreSQLWriting infinite scalability web applications with PHP and PostgreSQL
Writing infinite scalability web applications with PHP and PostgreSQL
 
L'ABC du BDD (Behavior Driven Development)
L'ABC du BDD (Behavior Driven Development)L'ABC du BDD (Behavior Driven Development)
L'ABC du BDD (Behavior Driven Development)
 
Caching on the Edge
Caching on the EdgeCaching on the Edge
Caching on the Edge
 
TDD with PhpSpec - Lone Star PHP 2016
TDD with PhpSpec - Lone Star PHP 2016TDD with PhpSpec - Lone Star PHP 2016
TDD with PhpSpec - Lone Star PHP 2016
 
Performance serveur et apache
Performance serveur et apachePerformance serveur et apache
Performance serveur et apache
 
Behat 3.0 meetup (March)
Behat 3.0 meetup (March)Behat 3.0 meetup (March)
Behat 3.0 meetup (March)
 
The Wonderful World of Symfony Components
The Wonderful World of Symfony ComponentsThe Wonderful World of Symfony Components
The Wonderful World of Symfony Components
 

Ähnlich wie Nodejs and WebSockets

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
 
Event-driven IO server-side JavaScript environment based on V8 Engine
Event-driven IO server-side JavaScript environment based on V8 EngineEvent-driven IO server-side JavaScript environment based on V8 Engine
Event-driven IO server-side JavaScript environment based on V8 EngineRicardo Silva
 
SockJS Intro
SockJS IntroSockJS Intro
SockJS IntroNgoc Dao
 
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
 
Node.js: The What, The How and The When
Node.js: The What, The How and The WhenNode.js: The What, The How and The When
Node.js: The What, The How and The WhenFITC
 
Jugando con websockets en nodeJS
Jugando con websockets en nodeJSJugando con websockets en nodeJS
Jugando con websockets en nodeJSIsrael Gutiérrez
 
Introduction to Vert.x
Introduction to Vert.xIntroduction to Vert.x
Introduction to Vert.xYiguang Hu
 
Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applicationsTom Croucher
 
KSDG-iSlide App 開發心得分享
KSDG-iSlide App 開發心得分享KSDG-iSlide App 開發心得分享
KSDG-iSlide App 開發心得分享Chia Wei Tsai
 
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
 
Nodejs a-practical-introduction-oredev
Nodejs a-practical-introduction-oredevNodejs a-practical-introduction-oredev
Nodejs a-practical-introduction-oredevFelix Geisendörfer
 
Cape Cod Web Technology Meetup - 2
Cape Cod Web Technology Meetup - 2Cape Cod Web Technology Meetup - 2
Cape Cod Web Technology Meetup - 2Asher Martin
 
introduction to node.js
introduction to node.jsintroduction to node.js
introduction to node.jsorkaplan
 
Node.js - A practical introduction (v2)
Node.js  - A practical introduction (v2)Node.js  - A practical introduction (v2)
Node.js - A practical introduction (v2)Felix Geisendörfer
 
Groovy & Grails eXchange 2012 vert.x presentation
Groovy & Grails eXchange 2012 vert.x presentationGroovy & Grails eXchange 2012 vert.x presentation
Groovy & Grails eXchange 2012 vert.x presentationStuart (Pid) Williams
 
Java script at backend nodejs
Java script at backend   nodejsJava script at backend   nodejs
Java script at backend nodejsAmit Thakkar
 

Ähnlich wie Nodejs and WebSockets (20)

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
 
Event-driven IO server-side JavaScript environment based on V8 Engine
Event-driven IO server-side JavaScript environment based on V8 EngineEvent-driven IO server-side JavaScript environment based on V8 Engine
Event-driven IO server-side JavaScript environment based on V8 Engine
 
SockJS Intro
SockJS IntroSockJS Intro
SockJS Intro
 
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
 
Node.js: The What, The How and The When
Node.js: The What, The How and The WhenNode.js: The What, The How and The When
Node.js: The What, The How and The When
 
5.node js
5.node js5.node js
5.node js
 
Jugando con websockets en nodeJS
Jugando con websockets en nodeJSJugando con websockets en nodeJS
Jugando con websockets en nodeJS
 
Introduction to Vert.x
Introduction to Vert.xIntroduction to Vert.x
Introduction to Vert.x
 
Node azure
Node azureNode azure
Node azure
 
Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applications
 
KSDG-iSlide App 開發心得分享
KSDG-iSlide App 開發心得分享KSDG-iSlide App 開發心得分享
KSDG-iSlide App 開發心得分享
 
The HTML5 WebSocket API
The HTML5 WebSocket APIThe HTML5 WebSocket API
The HTML5 WebSocket API
 
Introduction to Node.js
Introduction to Node.jsIntroduction to Node.js
Introduction to Node.js
 
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
 
Nodejs a-practical-introduction-oredev
Nodejs a-practical-introduction-oredevNodejs a-practical-introduction-oredev
Nodejs a-practical-introduction-oredev
 
Cape Cod Web Technology Meetup - 2
Cape Cod Web Technology Meetup - 2Cape Cod Web Technology Meetup - 2
Cape Cod Web Technology Meetup - 2
 
introduction to node.js
introduction to node.jsintroduction to node.js
introduction to node.js
 
Node.js - A practical introduction (v2)
Node.js  - A practical introduction (v2)Node.js  - A practical introduction (v2)
Node.js - A practical introduction (v2)
 
Groovy & Grails eXchange 2012 vert.x presentation
Groovy & Grails eXchange 2012 vert.x presentationGroovy & Grails eXchange 2012 vert.x presentation
Groovy & Grails eXchange 2012 vert.x presentation
 
Java script at backend nodejs
Java script at backend   nodejsJava script at backend   nodejs
Java script at backend nodejs
 

Kürzlich hochgeladen

UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdfUiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdfDianaGray10
 
Introduction to Matsuo Laboratory (ENG).pptx
Introduction to Matsuo Laboratory (ENG).pptxIntroduction to Matsuo Laboratory (ENG).pptx
Introduction to Matsuo Laboratory (ENG).pptxMatsuo Lab
 
Cybersecurity Workshop #1.pptx
Cybersecurity Workshop #1.pptxCybersecurity Workshop #1.pptx
Cybersecurity Workshop #1.pptxGDSC PJATK
 
Using IESVE for Loads, Sizing and Heat Pump Modeling to Achieve Decarbonization
Using IESVE for Loads, Sizing and Heat Pump Modeling to Achieve DecarbonizationUsing IESVE for Loads, Sizing and Heat Pump Modeling to Achieve Decarbonization
Using IESVE for Loads, Sizing and Heat Pump Modeling to Achieve DecarbonizationIES VE
 
Comparing Sidecar-less Service Mesh from Cilium and Istio
Comparing Sidecar-less Service Mesh from Cilium and IstioComparing Sidecar-less Service Mesh from Cilium and Istio
Comparing Sidecar-less Service Mesh from Cilium and IstioChristian Posta
 
NIST Cybersecurity Framework (CSF) 2.0 Workshop
NIST Cybersecurity Framework (CSF) 2.0 WorkshopNIST Cybersecurity Framework (CSF) 2.0 Workshop
NIST Cybersecurity Framework (CSF) 2.0 WorkshopBachir Benyammi
 
Bird eye's view on Camunda open source ecosystem
Bird eye's view on Camunda open source ecosystemBird eye's view on Camunda open source ecosystem
Bird eye's view on Camunda open source ecosystemAsko Soukka
 
UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6DianaGray10
 
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCost
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCostKubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCost
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCostMatt Ray
 
AI You Can Trust - Ensuring Success with Data Integrity Webinar
AI You Can Trust - Ensuring Success with Data Integrity WebinarAI You Can Trust - Ensuring Success with Data Integrity Webinar
AI You Can Trust - Ensuring Success with Data Integrity WebinarPrecisely
 
Crea il tuo assistente AI con lo Stregatto (open source python framework)
Crea il tuo assistente AI con lo Stregatto (open source python framework)Crea il tuo assistente AI con lo Stregatto (open source python framework)
Crea il tuo assistente AI con lo Stregatto (open source python framework)Commit University
 
AI Fame Rush Review – Virtual Influencer Creation In Just Minutes
AI Fame Rush Review – Virtual Influencer Creation In Just MinutesAI Fame Rush Review – Virtual Influencer Creation In Just Minutes
AI Fame Rush Review – Virtual Influencer Creation In Just MinutesMd Hossain Ali
 
UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...
UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...
UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...UbiTrack UK
 
COMPUTER 10 Lesson 8 - Building a Website
COMPUTER 10 Lesson 8 - Building a WebsiteCOMPUTER 10 Lesson 8 - Building a Website
COMPUTER 10 Lesson 8 - Building a Websitedgelyza
 
Salesforce Miami User Group Event - 1st Quarter 2024
Salesforce Miami User Group Event - 1st Quarter 2024Salesforce Miami User Group Event - 1st Quarter 2024
Salesforce Miami User Group Event - 1st Quarter 2024SkyPlanner
 
Artificial Intelligence & SEO Trends for 2024
Artificial Intelligence & SEO Trends for 2024Artificial Intelligence & SEO Trends for 2024
Artificial Intelligence & SEO Trends for 2024D Cloud Solutions
 
Building AI-Driven Apps Using Semantic Kernel.pptx
Building AI-Driven Apps Using Semantic Kernel.pptxBuilding AI-Driven Apps Using Semantic Kernel.pptx
Building AI-Driven Apps Using Semantic Kernel.pptxUdaiappa Ramachandran
 
9 Steps For Building Winning Founding Team
9 Steps For Building Winning Founding Team9 Steps For Building Winning Founding Team
9 Steps For Building Winning Founding TeamAdam Moalla
 

Kürzlich hochgeladen (20)

UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdfUiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
 
Introduction to Matsuo Laboratory (ENG).pptx
Introduction to Matsuo Laboratory (ENG).pptxIntroduction to Matsuo Laboratory (ENG).pptx
Introduction to Matsuo Laboratory (ENG).pptx
 
Cybersecurity Workshop #1.pptx
Cybersecurity Workshop #1.pptxCybersecurity Workshop #1.pptx
Cybersecurity Workshop #1.pptx
 
Using IESVE for Loads, Sizing and Heat Pump Modeling to Achieve Decarbonization
Using IESVE for Loads, Sizing and Heat Pump Modeling to Achieve DecarbonizationUsing IESVE for Loads, Sizing and Heat Pump Modeling to Achieve Decarbonization
Using IESVE for Loads, Sizing and Heat Pump Modeling to Achieve Decarbonization
 
20150722 - AGV
20150722 - AGV20150722 - AGV
20150722 - AGV
 
Comparing Sidecar-less Service Mesh from Cilium and Istio
Comparing Sidecar-less Service Mesh from Cilium and IstioComparing Sidecar-less Service Mesh from Cilium and Istio
Comparing Sidecar-less Service Mesh from Cilium and Istio
 
NIST Cybersecurity Framework (CSF) 2.0 Workshop
NIST Cybersecurity Framework (CSF) 2.0 WorkshopNIST Cybersecurity Framework (CSF) 2.0 Workshop
NIST Cybersecurity Framework (CSF) 2.0 Workshop
 
Bird eye's view on Camunda open source ecosystem
Bird eye's view on Camunda open source ecosystemBird eye's view on Camunda open source ecosystem
Bird eye's view on Camunda open source ecosystem
 
UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6
 
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCost
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCostKubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCost
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCost
 
AI You Can Trust - Ensuring Success with Data Integrity Webinar
AI You Can Trust - Ensuring Success with Data Integrity WebinarAI You Can Trust - Ensuring Success with Data Integrity Webinar
AI You Can Trust - Ensuring Success with Data Integrity Webinar
 
Crea il tuo assistente AI con lo Stregatto (open source python framework)
Crea il tuo assistente AI con lo Stregatto (open source python framework)Crea il tuo assistente AI con lo Stregatto (open source python framework)
Crea il tuo assistente AI con lo Stregatto (open source python framework)
 
AI Fame Rush Review – Virtual Influencer Creation In Just Minutes
AI Fame Rush Review – Virtual Influencer Creation In Just MinutesAI Fame Rush Review – Virtual Influencer Creation In Just Minutes
AI Fame Rush Review – Virtual Influencer Creation In Just Minutes
 
UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...
UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...
UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...
 
COMPUTER 10 Lesson 8 - Building a Website
COMPUTER 10 Lesson 8 - Building a WebsiteCOMPUTER 10 Lesson 8 - Building a Website
COMPUTER 10 Lesson 8 - Building a Website
 
Salesforce Miami User Group Event - 1st Quarter 2024
Salesforce Miami User Group Event - 1st Quarter 2024Salesforce Miami User Group Event - 1st Quarter 2024
Salesforce Miami User Group Event - 1st Quarter 2024
 
Artificial Intelligence & SEO Trends for 2024
Artificial Intelligence & SEO Trends for 2024Artificial Intelligence & SEO Trends for 2024
Artificial Intelligence & SEO Trends for 2024
 
20230104 - machine vision
20230104 - machine vision20230104 - machine vision
20230104 - machine vision
 
Building AI-Driven Apps Using Semantic Kernel.pptx
Building AI-Driven Apps Using Semantic Kernel.pptxBuilding AI-Driven Apps Using Semantic Kernel.pptx
Building AI-Driven Apps Using Semantic Kernel.pptx
 
9 Steps For Building Winning Founding Team
9 Steps For Building Winning Founding Team9 Steps For Building Winning Founding Team
9 Steps For Building Winning Founding Team
 

Nodejs and WebSockets

  • 1. Node.js and WebSockets Gonzalo Ayuso 2011 @gonzalo123 http://gonzalo123.wordpress.com https://github.com/gonzalo123
  • 2. Part 1. Node.js Part 2. WebSockets
  • 3. Node.js | What's node.js ● JavaScript on the server ● Written by Ryan Dahl ● Based on V8 (Google) ● Asynchronous event-driven model ● Similar in design to: ○ Event Machine (Ruby) ○ Twisted (Python)
  • 4. Node.js | Why? I/O needs to be done differently
  • 5. Node.js | Why? I/O needs to be done differently From: recordset = db.query("select * from Table"); render(recordset);
  • 6. Node.js | Why? I/O needs to be done differently Q: When will you add threads to JavaScript?” A: over your dead body Brendan Eich (creator of JavaScript)
  • 7. Node.js | Why? I/O needs to be done differently From: recordset = db.query("select * from Table"); render(recordset); To: db.query("select * from Table", function (recordset) { render(recordset) });
  • 8. Node.js | Why? I/O needs to be done differently From: recordset = db.query("select * from Table") render(recordset) To: db.query("select * from Table", function (recordset) { render(recordset) }); Design Goals ● No function should direct perform I/O. ● To read info from disk, network, ... there must be a callback
  • 9. Node.js | Show me the code! HTTP SERVER var http = require('http'); http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Hello Worldn'); }).listen(1337, "127.0.0.1"); console.log('Server running at http://127.0.0.1:1337/');
  • 10. Node.js | Show me the code! HTTP SERVER var http = require('http'); var total = 0; http.createServer(function (req, res) { res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end('Hi ' + total + 'n'); tot++; }).listen(1337, "127.0.0.1"); console.log('Server running at http://127.0.0.1:1337/');
  • 11. Node.js | Pros and Cons PROS ● Great I/O performance ● Just JavaScript. We all know JavaScript ● Community ● A lot of modules available https://github. com/joyent/node/wiki/modules ● npm
  • 12. Node.js | Pros and Cons PROS ● Great I/O performance ● Just JavaScript. We all know JavaScript ● Community ● A lot of modules available https://github. com/joyent/node/wiki/modules ● npm CONS ● Hosting ● We don't really know JavaScript ● Modules too young ● One thread, one single process for all ● Windows support
  • 13. Part 1. Node.js Part 2. WebSockets
  • 14. WebSockets | History Description of the problem: ● Real time communications in Browser
  • 15. WebSockets | History Description of the problem: ● Real time communications in Browser Imagine. Let's create simple chat client (5 years ago): Trivial problem with heavy clients, hard in browsers.
  • 16. WebSockets | History COMET (Wikipedia): Comet is a web application model in which a long-held HTTP request allows a web server to push data to a browser, without the browser explicitly requesting it.
  • 17. WebSockets | History COMET (Wikipedia): Comet is a web application model in which a long-held HTTP request allows a web server to push data to a browser, without the browser explicitly requesting it. Problem with COMET: ● Servers (keep-alive, MaxClients, ...) ● Clients
  • 18. WebSockets | History COMET (Wikipedia): Comet is a web application model in which a long-held HTTP request allows a web server to push data to a browser, without the browser explicitly requesting it. Problem with COMET: ● Servers (keep-alive, MaxClients, ...) ● Clients
  • 19. WebSockets | Short Polling / Long Polling Short Polling ● <meta http-equiv="refresh" content="5"> ● setInterval and setTimeout ● Inneficient ● Uses many resources (DB Connection, ...)
  • 20. WebSockets | Short Polling / Long Polling Short Polling ● <meta http-equiv="refresh" content="5"> ● setInterval and setTimeout ● Inneficient ● Uses many resources (DB Connection, ...) Long Pooling ● Looks like Real Time but it isn't RT
  • 21. WebSockets | Short Polling / Long Polling Short Polling ● <meta http-equiv="refresh" content="5"> ● setInterval and setTimeout ● Inneficient ● Uses many resources (DB Connection, ...) Long Pooling ● Looks like Real Time but it isn't RT It works? Yes It scales? No (Long Polling better but still No) Is your sysadmin happy? No
  • 22. WebSockets | Short Polling / Long Polling Short Polling ● <meta http-equiv="refresh" content="5"> ● setInterval and setTimeout ● Inneficient ● Uses many resources (DB Connection, ...) Long Pooling ● Looks like Real Time but it isn't RT It works? Yes It scales? No (Long Polling better but still No) Is your sysadmin happy? No
  • 23. WebSockets | HTML5 WebSockets This specification defines an API that enables Web pages to use the WebSocket protocol for two-way communication with a remote host.
  • 24. WebSockets | HTML5 WebSockets This specification defines an API that enables Web pages to use the WebSocket protocol for two-way communication with a remote host. That's means: ● The solution of the problem with RT at browser side
  • 25. WebSockets | HTML5 var ws = new WebSocket(url); ws.onopen = function() { // When the connection opens }; ws.onmessage = function() { // When the server sends data }; ws.onclose = function() { // When the connection is closed }; ws.send('Hi all'); // later... ws.close();
  • 26. WebSockets | HTML5 Cool but ...
  • 27. WebSockets | HTML5 Cool but ... Not all browsers support it
  • 28. WebSockets | socket.io Is there a solution?
  • 29. WebSockets | socket.io Is there a solution? http://socket.io/
  • 30. WebSockets | socket.io Is there a solution? http://socket.io/ Client <script src="/socket.io/socket.io.js"></script> <script> var socket = io.connect('http://localhost'); socket.on('news', function (data) { console.log(data); socket.emit('my other event', { my: 'data' }); }); </script>
  • 31. WebSockets | socket.io Is there a solution? http://socket.io/ Client <script src="/socket.io/socket.io.js"></script> <script> var socket = io.connect('http://localhost'); Server (node.js application) socket.on('news', function (data) { console.log(data); var io = require('socket.io').listen(80); socket.emit('my other event', { my: 'data' }); }); io.sockets.on('connection', function (socket) { </script> socket.emit('news', { hello: 'world' }); socket.on('my other event', function (data) { console.log(data); }); });
  • 32. WebSockets | socket.io http://socket.io/ Supported transports ● WebSocket ● Adobe® Flash® Socket ● AJAX long polling ● AJAX multipart streaming ● Forever Iframe ● JSONP Polling
  • 33. WebSockets | socket.io http://socket.io/ Supported transports Supported browsers ● WebSocket ● Internet Explorer 5.5+ ● Adobe® Flash® Socket ● Safari 3+ ● AJAX long polling ● Google Chrome 4+ ● AJAX multipart streaming ● Firefox 3+ ● Forever Iframe ● Opera 10.61+ ● JSONP Polling ● iPhone Safari ● iPad Safari ● Android WebKit ● WebOs WebKit
  • 34. References ● http://dev.w3.org/html5/websockets/ ● https://github.com/joyent/node/wiki/modules ● http://nodejs.org/ ● http://socket.io/ ● http://en.wikipedia.org/wiki/Push_technology ● http://www.youtube.com/watch?v=jo_B4LTHi3I ● http://gonzalo123.wordpress. com/category/technology/node-js/
  • 35. The End. Many thanks @gonzalo123 http://gonzalo123.wordpress.com