Socket.io with nodeJS

10566080Socket.io is an API that makes bidirectional connection toward your server and client, it’s often used in messaging web apps. The problem with bidirectional connection is that it’s really heavy on your server, so you want to use less as possible, so if we take a messaging app as example, instead of sending the whole message to the server, you’ll only push a notification trough your socket that will tell the other client to create an HTTP  request what you sent to database. Now that we’ve talked about it let’s see a few code snippet:

Server.js

io.sockets.on(“connection”, function(socket){
      //connection
      onlineUser++;
      //disconnect
      socket.on(“disconnect”, function(data){
           onlineUser–;
      });
     socket.on(‘sendNotification’, function (data) {
            console.log(“message”);
            socket.emit(‘notification’, data);
      });
});

here we are making our notification center in our server, we catch client input via socket.on whitch has 2 parameters (requestName, function).

socket.emit is used to send back data to our client, let’s see our client side!

app.js

var socket = io.connect(‘http:// localhost:8080’);  //init socket.io

socket.on(“notification”, function(data){
if(data.to == currentUserInfo.EMAIL && data.from == currentTalk){
getFriend(currentTalkId);
}
});

So, on the client side, we use socket.on to listen to the server in real time, in case the server would send a notification, then if there’s a notification, we are launching a function named getFriend() to update the content. on the client side, we can use socket.emit if we want to send data to the server.

I hope that I helped you, if you have any question, just ask.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Create a website or blog at WordPress.com

Up ↑

%d bloggers like this: