A software engineer bent on world bovine domination.
I write code at 99designs + Swiftly and on GitHub.

By Dennis Hotson.

Dec 07
Permalink

A simple chat server in Node.js

I had a quick go at writing a little chat server using Node.js.

I really like Node’s style. I’ve got to say that Javascript suits the evented / non-blocking model really well. Javascript is actually a pretty cool little language.

Getting started with Node.js was really easy. For me it was as simple as:

  1. git clone git://github.com/ry/node.git
  2. cd node
  3. ./configure
  4. make
  5. sudo make install
  6. .. save the code below as chat.js
  7. node chat.js
  8. .. clients can then connect with netcat. eg nc localhost 7000

Here’s the code, feedback is welcome. :-)

var net = require("net");

Array.prototype.remove = function(e) {
  for (var i = 0; i < this.length; i++) {
    if (e == this[i]) { return this.splice(i, 1); }
  }
};

function Client(stream) {
  this.name = null;
  this.stream = stream;
}

var clients = [];

var server = net.createServer(function (stream) {
  var client = new Client(stream);
  clients.push(client);

  stream.setTimeout(0);
  stream.setEncoding("utf8");

  stream.addListener("connect", function () {
    stream.write("Welcome, enter your username:\n");
  });

  stream.addListener("data", function (data) {
    if (client.name == null) {
      client.name = data.match(/\S+/);
      stream.write("===========\n");
      clients.forEach(function(c) {
        if (c != client) {
          c.stream.write(client.name + " has joined.\n");
        }
      });
      return;
    }

    var command = data.match(/^\/(.*)/);
    if (command) {
      if (command[1] == 'users') {
        clients.forEach(function(c) {
          stream.write("- " + c.name + "\n");
        });
      }
      else if (command[1] == 'quit') {
        stream.end();
      }
      return;
    }

    clients.forEach(function(c) {
      if (c != client) {
        c.stream.write(client.name + ": " + data);
      }
    });
  });

  stream.addListener("end", function() {
    clients.remove(client);

    clients.forEach(function(c) {
      c.stream.write(client.name + " has left.\n");
    });

    stream.end();
  });
});

server.listen(7000);


EDIT: Updated to match latest Node.js

Also, I wrote a CoffeeScript version.