Socket.IO using Node.JS and Express web framework

Tech Insights

Many of us have been playing around with Socket.IO to enable real-time communication. Still thought of sharing some (more) information.

In this post I will not go in deeper to explain the implementation as it’s clearly mentioned on the Socket.IO site. I will publish another post in detail on integrating Socket.IO with a Spring web app which might be a little more complex than the current thread.

So, for those who are beginning with Socket.IO, make sure Node.JS is installed. To check execute the command node -v in command line. Now create a json file which will be called the manifest file and place it inside a new directory. Here is an example of manifest file content:

{
“name”: “socket-chat-example”,
   “version”: “0.0.1”,
   “description”: “my first socket.io app”,
   “dependencies”: {
        “express”: “^4.10.2”,
        “socket.io”: “^1.5.1”
   }
}

This basically is the information about your project. In fact you don’t need to worry about the “dependencies” section. This can be populated with the command,

npm install –save

to install express and socket io modules, execute the following:

npm install –save express@4.15.2

npm install –save socket.io

Now to create js and html files for your app. Place the following code in the js file – index.js (can be any name)

var app = require(‘express’)();
var http = require(‘http’).Server(app);
var io = require(‘socket.io’)(http);

app.get(‘/’, function(req, res){
     res.sendFile(__dirname + ‘/index.html’);
});

io.on(‘connection’, function(socket){
     console.log(‘a user connected’);
});

http.listen(3000, function(){
     console.log(‘listening on *:3000’);
});

Here we create an http server object and pass it to the socket io instance. The event we handle here is ‘connection’. When a client connects, this event will be invoked. You can see that the http server listens on port 3000 once started. To start the setver run the command node index.js

Now comes the client/html part (the one we server using res.sendFile()). A sample code can be following:

/socket.io/socket.io.js
https://code.jquery.com/jquery-1.11.1.js

      var socket = io();

The js file – socket.io.js will be directly served to your app. The js code will load the socket io client and connect to the server. After any change restart the server by the same command and see the changes. That’s it.