SlideShare uma empresa Scribd logo
1 de 35
Baixar para ler offline
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

Mais conteúdo relacionado

Mais procurados

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
DefconRussia
 
Node Js Websocket Js Meetup Slides
Node Js Websocket Js Meetup SlidesNode Js Websocket Js Meetup Slides
Node Js Websocket Js Meetup Slides
Makoto Inoue
 

Mais procurados (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
 

Destaque

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
Davey Shafik
 
Why elasticsearch rocks!
Why elasticsearch rocks!Why elasticsearch rocks!
Why elasticsearch rocks!
tlrx
 
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
 

Destaque (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
 

Semelhante a Nodejs and WebSockets

SockJS Intro
SockJS IntroSockJS Intro
SockJS Intro
Ngoc Dao
 
Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applications
Tom Croucher
 
Java script at backend nodejs
Java script at backend   nodejsJava script at backend   nodejs
Java script at backend nodejs
Amit Thakkar
 

Semelhante a 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
 

Último

Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
Earley Information Science
 

Último (20)

A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 

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