Socket.IO is indeed an awesome technology to be used for building real-time applications.The great argument using Socket IO is sustainability, scalability and simplicity. Socket IO is cross-platform and we use it both with Node.JS, Ruby, Swift or Java. Also Supported natively by the standard platforms (i.e. iOS, Android, Javascript)
Whereas, socket io is javascript library which use event driven mechanism to update the data to all users asynchronously.
Real time example:
Take real time chat applications, any number of users can chat at same time and it will be updated to other users (like whatsapp or messenger groups). Server listens to the event that users sent messages, if it detects any messages from user, it updates to all remaining user ( Same principle like Observer pattern in java).
Important thing here is, application need not to be refreshed to get the latest data. any user do some events ( like whatsapp messages), server detects it and emit to the remaining users asynchronously that’s why it so become popular.
Program Demo:

Conceptual overview :
Two processes running on specific port of specific machine.
Either process can dial up the other process.
When connection is established, applications talk at a peer level, rather than one making requests and the other serving up those requests.

Demo URL: https://goo.gl/RcfRLs

* Client server programming :

For server code:

var static = require('node-static');
var http = require('http');
var sockets = [];
var file = new (static.Server)();
var _ = require('underscore')._;
var app = http.createServer(function (req, res) {
file.serve(req, res);
}).listen(process.env.PORT || 3000);

app.listen(3000, function () {
console.log('port 3000');
});

var io = require('socket.io').listen(app);
io.sockets.on('connection', function (socket) {
socket.on('joinGateRoom', function (room_name) {
socket.join(room_name);
});
socket.on('sendmsg', function (room_name, msg) {
io.sockets.in(room_name).emit('sentmsg', msg);
});
});

 

Live interaction is one of the good things about socket.io. Here, it gives you a realtime connection between your server and client browsers. Client makes request of server by sending data. Server sends replies to client. Protocol must be defined so, client/server understand can interpret messages.
*user 1

Code review for Snipet

$(document).ready(function () {
var socket = io.connect('http://localhost:3000/', {query: 'userId=ABCXYZ'});

socket.on('connect', function (data) {
socket.emit('joinGateRoom','LNroom');
});

$("#msgbox").keypress(function (event) {
if (event.which == '13') {
sendmsg();
event.preventDefault();
}
});

$("#msgbox1").keypress(function (event) {
if (event.which == '13') {
sendmsg1();
event.preventDefault();
}
});

function sendmsg()
{
var r = $("#msgbox").val();
socket.emit('sendmsg', 'LNroom', 'User1: '+r);
//add_message(r);
$("#msgbox").val('');
}

function add_message(m) {
$("#chatlog").append(m);
$("#chatlog").append("
");
}

socket.on('sentmsg', function (data) {
add_message(data);
});

});

 

Users 1 chat

 

—————————————————————————–
*user 2

Code review for Snipet

$(document).ready(function () {
var socket = io.connect('http://localhost:3000/', {query: 'userId=ABCXYZ'});

socket.on('connect', function (data) {
socket.emit('joinGateRoom','LNroom');
});

$("#msgbox").keypress(function (event) {
if (event.which == '13') {
sendmsg();
event.preventDefault();
}
});

$("#msgbox1").keypress(function (event) {
if (event.which == '13') {
sendmsg1();
event.preventDefault();
}
});

function sendmsg()
{
var r = $("#msgbox").val();
socket.emit('sendmsg', 'LNroom', 'User2: '+r);
//add_message(r);
$("#msgbox").val('');
}

function add_message(m) {
$("#chatlog").append(m);
$("#chatlog").append("
");
}

socket.on('sentmsg', function (data) {
add_message(data);
});

});

 

Users 2 chat

 

* Plugging Into Socket.IO: Advanced
Sometimes, you want to have the system set up to have a response from the server any time the server receives your messages. You can do this by sending functions to the server, which the server will then call “directly” and pass some data into it.

// Server Side

socket.on("getMessage", function(func) {
func("The Message");
});
// Client Side
socket.emit("getMessage", function(message) {
console.log(message);
});

 

When this is run, “The Message” will be posted in the client’s console. This might seem a bit like magic, but really it’s just a clever use of a proxy. The function itself isn’t actually being called. Rather a different function is being called in its place, which sends the data back to the client and has the actual function called there with the data that was sent. It’s a very nice system to ensure you receive acknowledgement of when the server receives your request. You could, of course, just rewrite the code like this and achieve the exact same effect, though.

// Server Side

socket.on("getMessage", function(func) {
socket.emit("theMessage", "The Message");
});
// Client Side
socket.emit("getMessage");
socket.on("theMessage", function(message) {
console.log(message);
});

 

It’s a little more code and it isn’t entirely clear from the client’s perspective that “theMessage” will be sent back immediately when “getMessage” is received, but it still works just as well.

Storing Client Data
Essentially Socket.IO has a special type of session storage that you can use to store information about each connected socket client. It’s also really simple to use

// Server Side

socket.on('set nickname', function (name) {
socket.set('nickname', name, function () {
socket.emit('ready');
});
});
socket.on('msg', function () {
socket.get('nickname', function (err, name) {
console.log('Chat message by ', name);
});
});

 

// Client Side

socket.emit('set nickname', user.nickname);
socket.on('ready', function () {
console.log('Connected !');
socket.emit('msg', message);
});

 

As you can see, it works well for storing a user’s nickname so that everyone in a chat can know who is sending the messages. Simply use socket.set and socket.get. Make sure you notice that they are asynchronous, so they require a callback if you want to do anything immediately after the value is saved or retrieved.

Broadcasting

By broadcasting, mean sending a message to everyone who is connected to the server. We already talked about this in the previous post, where I said that on the server side you could use io.sockets.emit rather than socket.emit to send a message to every client that is connected.

socket.on('chat message', function(msg) {
io.sockets.emit('message', msg);
});

 

There is potentially a problem with this setup, though it sends the message to the original client too. The client who sent “chat message” probably doesn’t need to receive it back. To get around this, there is a mechanism that allows you to send a message to everyone _except _the original client. Just use socket.broadcast.emit. The above code can now be written like this:

socket.on('chat message', function(msg) {
socket.broadcast.emit('message', msg);
});

 

Segmenting Users: Rooms and Namespaces

Sometimes you don’t want all of the users lumped up together in the same pool. You might want to send messages to some clients and not others. For this we have two different ways of segmenting users: Rooms and Namespaces.

Rooms

Users can be assigned to different rooms and then can be contacted when broadcasts are made to that room. First off, let’s learn how clients can be assigned to and removed from rooms. All of this is done on the server side. The client has no real power in controlling which rooms it is assigned to, except to send messages normally that the server responds to by changing whether you are in a room or not.

// Server Side

socket.on('addToRoom', function(roomName) {
socket.join(roomName);
});
socket.on('removeFromRoom', function(roomName) {
socket.leave(roomName);
});

 

Simply use socket.join and socket.leave to join and leave rooms, respectively. (You should try it if you’re interested) a socket can join multiple rooms at once. Now that you’re assigned to a room, whenever someone broadcasts to the entire room, you will be notified. Here’s how you broadcast to rooms:

// Broadcast to everyone in a room, except you
socket.broadcast.to(“room name”).emit(“your message”);
// Broadcast to everyone in a room, including you
io.sockets.in(“room name”).emit(“your message”);
And that’s all there is to rooms!

Namespaces

Namespaces aren’t technically intended for segmenting your users. Rather, they are used to allow you to have multiple connections to multiple Socket.IO servers, but only require the use of a single Socket.IO server. In other words, a single server acts like multiple servers that you can connect to separately. While the intention is different, it does work to segregate users.

Let’s set up the server side to allow multiple connections:

var io = require('socket.io').listen(80);
var chat = io
.of('/chat')
.on('connection', function (socket) {
// Send message to client like usual
socket.emit('a message', { that: 'only', socket: 'will get' });
// Broadcast message to everyone in this namespace
chat.emit('a message', { everyone: 'in', '/chat': 'will get' });
});
var news = io
.of('/news');
.on('connection', function (socket) {
socket.emit('item', { news: 'item' });
});

 

As you can see, all you do is replace sockets with of(‘/namespace’) when you start the on(‘connection’, function(){}) call. This creates a segment of connections that you can keep separate from other connections. As you can see, this setup allows you to broadcast to everyone in this namespace too.

Now we need the clients to connect to them separately. Simply just create separate connections to each of the namespaces and you’re all set.

var chat = io.connect('http://localhost/chat'),
news = io.connect('http://localhost/news');
chat.on('connect', function () {
chat.emit('connectedToChat');
});
news.on('news', function () {
news.emit(' connectedToNews');
});

 

Just add the namespace to the end of the normal URL and you’ll connect to the Socket.IO server with that namespace. You can treat chat or news exactly the same way you used to treat socket in the single-connection scenarios.

Configuration

Socket.IO has many configurable options, so they implemented a way to configure it. Here’s a quick look at how to do it.

io.configure('production', function(){
io.enable('browser client etag');
io.set('log level', 1);
io.set('transports', ['websocket', 'flashsocket', 'xhr-polling']);
});

 

First, call io.configure sending in the environment you want the configuration to be set up for and a function. Inside the function, you can use io.enable (which just sets the option’s value to true), io.disable (which sets the value to false), and io.set (which sets the value to whatever the second argument is) to change all of the options available to Socket.IO.

If you want more information on changing the environments and which options are available, I recommend you take a look at the wiki page about configuring Socket.IO.

Setting and Getting option values

-getsockopt() : gets the current value of a socket option.
int getsockopt( int sockfd, int level,int optname, void *opval, socklen_t *optlen);
-setsockopt() : used to set the value of a socket option.
int setsockopt( int sockfd, int level, int optname,const void *opval, socklen_t optlen);

 

SO_ERROR :The value is an error indicator value similar to errno It is readable only!
by calling getsockopt() function

SO_KEEPALIVE :keep TCP alive. This means that you will be able to check your connected socket (also known as TCP sockets), and determine whether the connection is still up and running or if it has broken.

SO_LINGER : Setting SO_LINGER means the closing process can determine that the peer machine has received the data
but not that the data has been read()
The typical reason to set a SO_LINGER timeout of zero is to avoid large numbers of connections sitting in the TIME_WAIT state, tying up all the available resources on a server.

Conclusion

Socket.IO has proven itself to be a great replacement for straight WebSockets. It allows amazing customizability and a wonderfully simple API for enabling real-time 2-way communication between a server and client. It’s definitely worth taking a look at.As we know, technologies are now outdated in a near future and Socket IO is a simple protocol. You some years it will be easy to migrate if you want to use something else.

Want to work with us? We're hiring!