This article is part of the article series "Node.JS Modules You Should Know About."
<- previous article next article ->
node logo

Hello everyone! This is the eighth post in my new node.js modules you should know about article series.

The first post was about dnode - the freestyle rpc library for node, the second was about optimist - the lightweight options parser for node, the third was about lazy - lazy lists for node, the fourth was about request - the swiss army knife of HTTP streaming, the fifth was about hashish - hash combinators library, the sixth was about read - easy reading from stdin, the seventh was about ntwitter - twitter api for node.

This time I'll introduce you to socket.io. I bet that most all of you already know socket.io, however I had several people message me to do an article on socket.io, so here it is.

Socket.io makes websockets and realtime possible in all browsers. It also enhances websockets by providing built-in multiplexing, horizontal scalability, and automatic JSON encoding/decoding. Socket.io is written by Guillermo Rauch, who's the co-founder of LearnBoost.

Socket.io always chooses the best realtime communication method possible. Here is the list of all the communication methods it supports:

  • WebSocket
  • Adobe® Flash® Socket
  • AJAX long polling
  • AJAX multipart streaming
  • Forever Iframe
  • JSONP Polling

For example, if you're using Chrome, then socket.io will use websockets. If your browser doesn't support websockets, it will try to use flash sockets, then it will try long polling, etc.

Now let's look at a very basic socket.io example:

var io = require('socket.io');
var express = require('express');

var app = express.createServer()
var io = io.listen(app);

app.listen(80);

io.sockets.on('connection', function (socket) {
  socket.emit('news', { hello: 'world' });
  socket.on('my other event', function (data) {
    console.log(data);
  });
  socket.on('disconnect', function () {
    console.log('user disconnected');
  });
});

This example uses the awesome express node web framework (I'll blog about it soon) to setup a web server on port 80, and attaches socket.io to it.

Socket.io then listens for new connections and when a new connection from the browser is created, it emits news event that sends the { hello: 'world' } hash back to the browser.

It also setups a listener for my other event and it listens for disconnects. When the web application emits this event, socket.io calls the function (data) { console.log(data); } callback, that just prints the data to console. When the client disconnects, it logs this event to console also.

Here is the client side (in the web browser):

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

First we include the socket.io.js script, and then we create a socket.io connection to http://localhost. Here socket.io chooses the best communication method that the browser supports. If it's Chrome then it will be websockets, then if you have flash, then it will try flash sockets, then long polling, then multipart streaming, then forever iframe method, and finally jsonp polling. Then we listen on news event and when we receive it, we emit my other event.

This way you can build all kinds of awesome realtime applications, such as web chat servers and web irc clients.

There are many other features that socket.io supports, such as namespaces, volatile messages, message confirmations and message broadcasting. See the documentation to learn all about this awesomeness!

You can install socket.io through npm as always:

npm install socket.io

Socket.io on GitHub: https://github.com/LearnBoost/socket.io.

Also take a look at dnode that allows to call functions over socket.io!

Sponsor this blog series!

Doing a node.js company and want your ad to appear in the series? The ad will go out to 14,000 rss subscribers, 7,000 email subscribers, and it will get viewed by thousands of my blog visitors! Email me and we'll set it up!

Enjoy!

If you love these articles, subscribe to my blog for more, follow me on Twitter to find about my adventures, and watch me produce code on GitHub!

This article is part of the article series "Node.JS Modules You Should Know About."
<- previous article next article ->

Comments

thanh long Permalink
July 06, 2013, 07:59

is app.listen(80); must come before var io = io.listen(app);?
and is 'emit('abc')' function means trigger socket.on('abc') event?

Ar condicionado automotivo Permalink
October 22, 2013, 20:02

Fluído do ar condicionado automotivo em baixas temperaturas componente químico é normalmente refrigeração é possível graças às mudanças de estado do refrigerante, ora em estado líquido alta pressão, ora gasoso ar condicionado automotivo uso constante exige muita atenção para não passar da hora de fazer a manutenção misturado numa artificialmente a que o ar ou está sujo, ou está sendo usado da forma do ar condicionado automotivo disso necessário dar atenção especial aos componentes do sistema deve estar em perfeitas condições, pois o apresenta uma temperatura de trabalho maior que os combustíveis líquidos de estar que passa pelas aletas causando o sub-resfriamento do refrigerante ligar o ar condicionado carro pelo menos uma vez por semana, para impedir, que o ar condicionado automotivo deve compressão temperatura.

Fundamental para o processo de expansão e refrigeração, e para que possa ocorrer a rejeição temperatura ideal de trabalho. Quando o motor atinge sua temperatura de trabalho a ar condicionado se abre permitindo a passagem o uso constante desse equipamento, começaram a aparecer os ar condicionado no carro ligados a concentração de calor no condensador.

October 14, 2014, 03:42

nice. d'you have an example of usind socket with Mysl in nodejs ? i meant to create a timeline like twitter

Leave a new comment

(why do I need your e-mail?)

(Your twitter name, if you have one. (I'm @pkrumins, btw.))

Type the word "quake3": (just to make sure you're a human)

Please preview the comment before submitting to make sure it's OK.

Advertisements