Websockets & Sockets.io

Tweet about this on TwitterShare on LinkedIn0Share on Google+0Share on Reddit0Buffer this pageFlattr the authorEmail this to someonePrint this page

Websockets & Sockets.io

Today’s web is more on the lines of demand and supply. A user request a page & the server dispatches it. After that the server is not aware who the client is (unless we maintain a session). For every other request from the same client to the same server, a new connection needs to be opened, every single time.

Below is screenshot of page loading time of my blog’s home page using this tool

Screen Shot 2014-03-10 at 9This is a call stack for the first request that was fired from one of the pingdom servers/browsers to my blog. It actually took ~.9 of a second to resolve the host, connect to my server & receive the first byte of data. This looks cute when we load the page for the first time, But if I keep executing the same test for 3-4 times,

Screen Shot 2014-03-10 at 9.53.56 AMI am still spending ~.4 of a second to do same steps again. This is where web sockets fit in.

Contents

Excerpt from wikipedia

WebSocket is a protocol providing full-duplex communications channels over a single TCP connection. The WebSocket protocol makes possible more interaction between a browser and a web site, facilitating live content and the creation of real-time games.

This is made possible by providing a standardized way for the server to send content to the browser without being solicited by the client, and allowing for messages to be passed back and forth while keeping the connection open. In this way a two-way (bi-directional) ongoing conversation can take place between a browser and the server.

WebSocket is designed to be implemented in web browsers and web servers, but it can be used by any client or server application. The WebSocket Protocol is an independent TCP-based protocol.

The only difference between websockets and the traditional model of communication is that, websockets keeps connection alive with all its clients till they disconnect.

Browser Support

There are 2 parts to the WebSockets. One the client from where the request originates & one the server, where the request gets served. We cannot use any server for a socket based connection, as most of the traditional servers do not respond well to concurrent open sockets. So each server side technology has their own WebSockets supported server. For Javascript, we have Node!! And as you can see from the below table, all clients do not support the Sockets too!

Sockets.IO

To make our lives easy (or lazy), some awesome folks built a Cross Browser WebSocket utility that will take care of both your server & client side communication. Isn’t this cool!!

Sockets.io in simple terms is a polyfill {kind of like jQuery for your DOM manipulation & Ajax calls}, uses websockets prototcol if the client supports or switches to other ways of implementing sockets like long pooling etc. If you want to know more about how socket.io works, here is a link.

Node – Sockets Server

So, lets set up a socket server via Node & have some fun. If you are not familiar with Node, follow this & this.

Next, let’s create a new folder and name it myWebSocketApp. Now, open terminal/prompt & cd into myWebSocketApp folder. Run npm init & fill as below

Screen Shot 2014-03-10 at 10.54.38 AMThis is a quick way to init a new Node project. Now lets add sockets.io to our project. run   npm install socket.io --save-dev.

Next, lets create a new file called index.js inside myWebSocketApp folder. This is our server! (simpler times are back!!). Paste the below code (I will explain this in a moment, lets see some output first!!)

And now our client, create a new file called index.html at the same location and add the below code

Running the Sockets App

Now back to terminal/prompt & run  node index.js. You should see a message

info  - socket.io started

If you see any error like

check if 1234 port is already used. And change to a new port & update both index.js & index.html.

Now, lets head to a browser and navigate to  http://localhost:1234. You should see a page like

Screen Shot 2014-03-10 at 7.40.17 PMAnd your terminal/prompt should reflect something like

Screen Shot 2014-03-10 at 7.43.48 PMEverything is pretty readable!

Understanding the Server & Client

Now, lets take a quick at the index.js file.

We will start of by requiring the http server, socket.io and fs – to interact with the file system. Now, we will ask the server to list to port 1234.

The handler function will do a simple task of picking the index.html file & dispatching it to the requested client, when any client reaches http://localhost:1234 .

Finally we register a couple of events with the server. First the “connection”, this method will get triggered when a new connection is established. Inside this, we emit a message to the client with a name “news”. And we register another method with a name “my other event”, this will get triggered only when the server receives a “my other event” event from the current client. Sounds confusing? Not really. You will get a clear picture when you see the other end of the communication.

Now, lets open up our client piece of code, index.html.

So this is what threw me off the first time around. Line 3 has a reference to a socket.io.js. But we never copied or created such a resource, how was it working?? Well thats what socket.io does. It intercepts the request from the client (take a look at line no 2 in index.js) & identifies the required version of the socket.io & dispatches it.

You should never put a static file in place!.

Line 5 connects the client to the socket, declared on the specified host & port. Next, it registers 2 events, “news” & “my other event”. Event “news” will be triggered by the server & the client will emit “my other event”.

So this is the big picture,

Step 1: when the page loads, the server will respond with a HTML page, and the client will load the page.

Step 2: Socket will be initiated & will connect to the host specified.

Step 3: This will trigger the “connection” method on the server. & the server will emit a “news” event & register a “my other event”.

Step 4: The client side “news” event gets triggered and console logs the received data & then emits “my other event”.

Step 5: The server will receive the “my other event” & console logs the data sent from client on the node console.

Quite an awesome interaction right? By now you must have got an ideas as how sockets can be used, like say a chat application. “Client 1″ emits a message to the server & server will emit a message to all its connected “Clients” & so on.

Debugging Sockets on Chrome

Chrome has a simple interface that will show a list of interactions that happens between the client & server, kind of like a debugger.

For this, make sure your server is running ( node index.js ) & then navigate to  http://localhost:1234  in chrome. Then open up the developer tools (ctrl + shft + I or cmd + shft + I) then click on the network tab. Refresh the page again & you should see something like

Screen Shot 2014-03-10 at 8.17.40 PM

Click on the last request, that consist of a random alpha-numeric string (this is our socket id for this session. This is how our server recognises us) and you should see something like

Screen Shot 2014-03-10 at 8.17.54 PM

Sweet right! Each communication between the server & client is tracked as a frame.

Just for fun, leave your server running, have a cup of coffee & come back. You will see a few logs on your server console like

This is how the connection is kept active.

I hope you have got an idea on how Sockets work & how we can implement a simple socket app. I will write another post leveraging sockets to build a Chat application.


Thanks for reading! Do comment.
@arvindr21

Tweet about this on TwitterShare on LinkedIn0Share on Google+0Share on Reddit0Buffer this pageFlattr the authorEmail this to someonePrint this page
  • David Azar

    Thanks for this whole series of articles, they’ve been super useful..
    For some reason, i cant run the index.js file.
    i do “node index.js” and it just keeps hanging.

  • Christian Bertram

    Thanks, this gives a really quick and easy understanding of websockets!