Introduction to WebSockets – Server, Client examples using Node.js

Initially the paradigm about web was Client/Server model, in which client’s job is to request data from a server, and a server’s job is to fulfill those requests. This paradigm fulfills the web requirement for number of years, but later on with Introduction of AJAX makes us enable to communicate with server asynchronously.

Now using AJAX it was easy to communicate with server but we still need more power when talk in term of real time applications. an simple example http request could be like bellow.

So every time you make an HTTP request a bunch of headers and cookie data are transferred to the server and in response you will response header along with data. If you are working on a real time application or game running in browser, you will have problems running things smoothly because every request contain a lot of unnecessary data which is not needed every time you make request to server. so here comes WebSockets which is a way of creating a persistent, low latency connection that can support transactions initiated by either the client or server.
Using WebSockets you can start a bidirectional connection where client/server can use to start send data at any time. Client establishes connection through a process called WebSocket handshake, client will send regular HTTP request to the server – upgrade header is included in this request to let server know that a client want to establish a WebSocket connection.

Now if the server supports the WebSocket protocol, it will send upgrade header back in the response.

After handshake is complete the initial HTTP connection is replaced by a WebSocket connection that uses TCP/IP connection and now either party can starting sending data.

A simple client side connection is like bellow.

To send a message through the WebSocket connection you call the send() method. You can send both text and binary data through a WebSocket.

Now if you want to create a simple socket server using Express.js and Socket.IO.

Server is now listening at port 3000, which can recieve and send data.