archive / 2011

A chat server in 50 lines with Node.js and Socket.IO

My first encounter with Node.js 0.4: a minimal real-time chat with Socket.IO, and what feels different coming from PHP.

For a few months now I’ve been reading about Node.js everywhere. JavaScript on the server, non-blocking I/O, a single thread handling thousands of connections. For someone who writes PHP all day and knows JavaScript mainly as “that thing you make slideshows with”, it sounded like an odd combination.

Last weekend I finally tried it. The goal: a chat room that works in real time, without the browser having to poll every second. The result fits in fifty lines.

Installing#

I’m using Node 0.4.11, the current stable release. The 0.5 series is the development branch, so I’m staying away from that for now. On my Ubuntu laptop I compiled it from source:

wget http://nodejs.org/dist/node-v0.4.11.tar.gz
tar xzf node-v0.4.11.tar.gz
cd node-v0.4.11
./configure
make
sudo make install
node -v

Then npm, the package manager, and Socket.IO in a fresh project folder:

curl http://npmjs.org/install.sh | sh
mkdir chat && cd chat
npm install socket.io

Since npm 1.0, packages are installed locally into node_modules in your project folder by default. That’s a lot tidier than installing everything globally.

The server#

Socket.IO is a library that handles real-time communication between browser and server. If the browser supports WebSockets, it uses them. If not, it falls back to Flash, long polling or other tricks. As a developer you don’t have to care.

server.js:

var http = require('http');
var fs = require('fs');

var server = http.createServer(function (req, res) {
    fs.readFile(__dirname + '/index.html', function (err, data) {
        if (err) {
            res.writeHead(500);
            return res.end('Could not load index.html');
        }
        res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
        res.end(data);
    });
});

var io = require('socket.io').listen(server);
server.listen(8080);

io.sockets.on('connection', function (socket) {

    socket.on('name', function (name) {
        socket.set('name', name, function () {
            io.sockets.emit('system', name + ' joined');
        });
    });

    socket.on('message', function (text) {
        socket.get('name', function (err, name) {
            io.sockets.emit('message', { name: name || 'anonymous', text: text });
        });
    });

    socket.on('disconnect', function () {
        socket.get('name', function (err, name) {
            if (name) {
                socket.broadcast.emit('system', name + ' left');
            }
        });
    });
});

What’s going on here:

  • http.createServer creates a web server. No Apache, no .htaccess, just a function that gets called for every request. Jef looked over my shoulder and muttered something unintelligible.
  • fs.readFile is asynchronous. You pass a callback, and Node carries on handling other requests in the meantime. That’s the whole idea.
  • io.sockets.emit sends an event to everyone. socket.broadcast.emit sends it to everyone except the current socket.
  • socket.set and socket.get store data per connection, in this case the user’s name. They’re asynchronous too, hence the callbacks.

The client#

index.html:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Chat</title>
    <style>
        #messages { list-style: none; padding: 0; height: 300px; overflow: auto; }
        .system { color: #888; font-style: italic; }
    </style>
</head>
<body>
    <ul id="messages"></ul>
    <form id="form">
        <input id="text" autocomplete="off">
        <button>Send</button>
    </form>

    <script src="/socket.io/socket.io.js"></script>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
    <script>
    $(document).ready(function () {
        var socket = io.connect();
        var name = window.prompt('What is your name?') || 'anonymous';

        socket.emit('name', name);

        function show(text, className) {
            $('<li>').text(text).addClass(className || '').appendTo('#messages');
            $('#messages').scrollTop($('#messages')[0].scrollHeight);
        }

        socket.on('message', function (data) {
            show(data.name + ': ' + data.text);
        });

        socket.on('system', function (text) {
            show(text, 'system');
        });

        $('#form').submit(function () {
            var text = $('#text').val();
            if (text) {
                socket.emit('message', text);
                $('#text').val('');
            }
            return false;
        });
    });
    </script>
</body>
</html>

Notice /socket.io/socket.io.js: that file doesn’t exist in your folder. Socket.IO intercepts that URL itself and serves the client library. A bit magical, but handy.

I’m using .text() rather than .html() to display messages. Otherwise anyone in the chat can inject HTML and <script> tags. I tested it. It works. My colleagues were less thrilled when their screens started flashing.

Start it up:

node server.js

Open http://localhost:8080 in two browser windows and chat with yourself. It’s more fun to send your IP address around the office.

What feels different from PHP#

  • The server keeps running. In PHP every request starts from scratch. In Node your process stays alive, and a variable at the top of your file is shared between all users. That’s powerful, but also dangerous: one uncaught throw and your whole chat goes down. For everyone.
  • Callbacks everywhere. After an hour I was three functions deep. I now understand why people complain about “callback spaghetti”.
  • Changing code means restarting. No hitting F5 in the browser. I quickly found out there are tools that restart your server automatically when a file changes.
  • Deploying isn’t “upload the files”. You need a process that keeps running and gets restarted when it crashes. On the shared hosting our clients use, that’s simply not possible.

So, now what?#

For the sites we build at the agency, this isn’t for us yet. A bakery doesn’t need real-time chat, and our clients are on shared hosting with PHP. But for anything that needs to be “live”, like notifications, dashboards or several people editing the same document, this feels like the right tool.

I’ll keep following it. The docs are on nodejs.org, and I’m curious about the next stable release, which is supposed to run on Windows as well.

    Tip: / opens search, ↑↓ to select, ↵ to open.