Getting started with Socket.IO and Node.js

Node.js is not the cure for everything, however, it can certainly makes working with Websockets very easy when using the Socket.io library. Using websockets you can easily build realtime applications and even multi-player games. Today I’ll show you how to easily build a simple chat program using Node.js and Socket.io.

Note: To go through this article you will need to have Node.js installed and working correctly. You will also need some sort of text editor, I’ll be using WebStorm but anything you wish to use should work. Some of the code in this article has been modified from this excellent source: http://book.mixu.net/ch13.html

On you computer create a new folder somewhere convenient called: chat. Inside that folder you can add two files called: app.js and index.html

The above code is pretty bare minimum for a chat server. The server sends the index.html file and listens for any incoming websockets. If you were to send a message like “hi” the format would look something like the following:

{"name":"message","args":["hi"]}

The index.html page is also very minimal and looks like the following:

Incoming Chat:

The webpage is not very attractive but it works. Open two browsers preferably ones that support WebSockets (Chrome or Safari will work).

The next step is to install socket.io by doing the following in a terminal (or command prompt):