Communication between Client & Server

📄 Table of Contents

A TCP socket is an endpoint over which two programs can communicate using a network. Each socket is bound to a port number that identifies the application. For example: “http” communicates over port 80. So, a web server listens for http connections on port 80.


A websocket is a standard BI-directional TCP socket between the client & the server. The socket starts out as a HTTP connection and then upgrades to a “TCP” socket after a HTTP handshake. After the handshake, either side can send data.


A session is a way of identifying that subsequent connections come from the same client, this allows the server to maintain state, so for example the user stays logged in.

This is often done using a cookie but can also be done by other methods such as passing a query string parameter. After a certain amount of time with no requests for a given session the server will expire it, this may cause the user to have to log back in or start filling out forms from scratch.

A cookie is a text file that gets submitted along with each web request to a given server. Cookies have an expiry after which they no longer get submitted, it is either a date and time or when the user closes the browser. The web server can store arbitrary text data in the cookie and then retrieve that data when the user next accesses the web site. Cookies are most frequently used to store a way of identifying a user in order to provide state such as a session or to display appropriate advertising or other content.


Also, chrome will not show the cookies in the “inspect element” Network tab.

◉ JavaScript Session

Basically, a session is a storage that consists of information on server-side. JavaScript Session will be in active state till the user interacts with a website or web application.

As a replacement to cookies that store constantly changing data in user’s browser, a unique identifier is stored on client side known as Session Id.

Whenever the browser makes an HTTP request, the session id is passed to the web server every time. This session id pairs up with internal database and retrieves the variables as per the request.

Sometimes, server cannot identify the client from where it is getting requests. This happens when continuous requests and responses are received from the same client to the server. So, JavaScript Session tracking is used by providing session id’s to maintain the conversational state.

JavaScript is a client-side application and Session is a server-side application.

So, there will be two options to set the JavaScript Session values.

  • On the client side, query the session value using AJAX on the server.
  • Sending the session value from the server to a client using HiddenField. So, JavaScript updates this value and send back to the server using submission or postback.

To store the data for only one session, sessionStorage object can be used. In sessions, the data will be deleted when the user closes the browser tab.

Key Points

  • Session will run on Server-side.
  • Session stores the data only till the browser is active.
  • Session is stored using session.Storage object.


The sessionStorage property accesses a session Storage object for the current origin. sessionStorage is similar to localStorage; the difference is that while data in localStorage doesn't expire, data in sessionStorage is cleared when the page session ends.

  • A page session lasts as long as the browser is open, and survives over page reloads and restores.
  • Opening a page in a new tab or window creates a new session with the value of the top-level browsing context, which differs from how session cookies work.
  • Opening multiple tabs/windows with the same URL creates sessionStorage for each tab/window.
  • Closing a tab/window ends the session and clears objects in sessionStorage.

Data stored in sessionStorage is specific to the protocol of the page.In other words, will have separate storage than

// Save data to sessionStorage
sessionStorage.setItem('key', 'value');

// Get saved data from sessionStorage
let data = sessionStorage.getItem('key');

// Remove saved data from sessionStorage

// Remove all saved data from sessionStorage

Before diving to the need of Web sockets, it is necessary to have a look at the existing techniques, which are used for duplex communication between the server and the client. They are as follows −

  • Polling
  • Long Polling
  • Streaming
  • Postback and AJAX
  • Websockets (inbuild in HTML5)

◉ AJAX (Asynchronous Javascript and XML)

  • AJAX is based on Javascript’s XmlHttpRequest Object.
  • XmlHttpRequest Object allows execution of the Javascript without reloading the complete web page.
  • AJAX sends and receives only a portion of the web page.

The major drawbacks of AJAX in comparison with Web Sockets are −

  • They send HTTP headers, which makes total size larger.
  • The communication is half-duplex.
  • The web server consumes more resources.

◉ WebSocket (inbuilt in HTML5)

Before its existence, all communication between the web clients and the servers relied only on HTTP.

A WebSocket is nothing but a persistent connection between the client and the server. This is a communication protocol providing full-duplex communication channels over a single TCP connection.

WebSocket is a standard protocol for two-way data transfer between a client and a server. The webSocket protocol is built on TCP, NOT running on over HTTP protocol.

The websockets are designed to stay open. However, websocket connection is LOST when page is refreshed.

Once a connection has been established between the client and the server, an open event is fired from the Web Socket instance. Error are generated for mistakes, which take place during the communication. It is marked with the help of onerror event. The onerror event is always fired when something wrong occurs between the communications. The event onerror is followed by a connection termination, which is a close event.

A good practice is to always inform the user about the unexpected error and try to reconnect them.

socket.onclose = function(event) {
console.log("Error occurred.");

// Inform the user about the error.
var label = document.getElementById("status-label");
label.innerHTML = "Error: " + event;

You can also go with the method to have the server close the connection. Through this, the websocket will fire an onclose event and would amazingly continue attempting to make the connection.

In addition, when the server is listening again the connection will be automatically re-established.

The WebSocket.send() method enqueues the specified data to be transmitted to the server over the WebSocket connection:

WebSocket.send("Hello server!");

WSS supports only “string” while fetching and sending. So, if we have to send some object to websocket, simply stringify the object using


◉ WebSocket vs. Long polling HTTP

Using HTTP polling is hugely disadvantageous as it wastes resource and may cause connection time out.

Here is brief explanation of the difference between HTTP long polling via AJAX and WebSockets only.

With long polling via AJAX, the server keeps polling WSGI server to check any new data. HTTP is not meant for keeping the connection open for the server to send frequent data to a client. The following is a sort of old way of implementing long polling via AJAX requests.

Building a real-time web application is a bit challenging one, where we need to consider how we are going to send our data from the server to the client.

A few ways to implement these:

  • Long/short polling (client pull)
  • WebSockets (server push)
  • Server-Sent Events (server push)

Client pull — client asking server for updates at certain regular intervals

Server push — server is proactively pushing updates to the client (reverse of client pull)

🔘 Short polling (a.k.a. AJAX based timer):

  • Pros: simpler, not server consuming (if the time between requests is long).
  • Cons: bad if you need to be notified WHEN the server event happens with no delay. Example (ItsNat based)

🔘 Long polling (a.k.a. Comet based on XHR)

  • Pros: you are notified WHEN the server event happens with no delay.
  • Cons: more complex and more server resources used. Example (ItsNat based)


  • Web Socket is a stateful protocol whereas HTTP is a stateless protocol.
  • Web Socket connections can scale vertically on a single server whereas HTTP can scale horizontally. There are some proprietary solutions for Web Socket horizontal scaling, but they are not based on standards.
  • HTTP comes with a lot of other goodies such as caching, routing, and multiplexing. All of these need to be defined on top of Web Socket.

Server Side Events (SSE)

Server Sent Events are a standard allowing browser clients to receive a stream of updates from a server over a HTTP connection without resorting to polling. Unlike WebSockets, Server Sent Events are a one way communications channel — events flow from server to client only.

You might consider using Server Sent Events when you have some rapidly updating data to display, but you don’t want to have to poll the server. Examples might include displaying the status of a long running business process, tracking stock price updates, or showing the current number of likes on a post on a social media network.


When working with Server Sent Events, communications between client and server are initiated by the client (browser). The client creates a new JavaScript EventSource object, passing it the URL of an endpoint which is expected to return a stream of events over time.

The server receives a regular HTTP request from the client (these should pass through firewalls etc like any other HTTP request which can make this method work in situations where WebSockets may be blocked). The client expects a response with a series of event messages at arbitrary times. The server needs to leave the HTTP response open until it has no more events to send, decides that the connection has been open long enough and can be considered stale, or until the client explicitly closes the initial request.

Every time that the server writes an event to the HTTP response, the client will receive it and process it in a listener callback function. The flow of events looks roughly like this:

Flow of events between Client and Server

Message Format

The Server Sent Events standard specifies how the messages should be formatted, but does not mandate a specific payload type for them.

A stream of such events is identified using the Content-Type “text/event-stream”. Each event is formatted using a set of colon separated key/value pairs with each pair terminated by a newline, and the event itself terminated by two newlines.

Client (Browser) Implementation

The client connects to the server to receive events by declaring a new EventSource object, whose constructor takes a URL that emits a response with Content-Type “text/event-stream”.

Event handler callback functions can then be registered to handle events with a specific type (event key/value pair is present). These handlers are registered using the addEventListener method of the EventSource object.

Additionally, a separate property of the EventSource object, onmessage (annoyingly not using camelCase) can be set to a callback function which will receive events that do not have the optional event key/value pair set.

Server Side Implementation

While the client implementation has to be JavaScript as it runs in the browser, the server side can be coded in any language. As this demo was originally put together for a JavaScript Meetup group I used Node.js. The server side could just as easily have been built in Java, C, C#, PHP, Ruby, Python, Go or any language of your choosing.

The server implementation should be able to:

  • Receive a HTTP request.
  • Respond with one or more valid server sent event messages, using the correct message format.
  • Tell the client that the Content-Type being sent is “text/event-stream” indicating that the content will be valid server sent event messages.
  • Tell the client to keep the connection alive, and not cache it so that events can be sent over the same connection over time, safely reaching the client.

Code for a basic example of a server in Node.js that does this and sends an event approximately every three seconds is shown below.

const http = require('http');http.createServer((request, response) => {
response.writeHead(200, {
Connection: 'keep-alive',
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache'
}); let id = 1;
// Send event every 3 seconds or so forever...
setInterval(() => {
`event: myEvent\nid: ${id}\ndata:This is event ${id}.`
}, 3000);

Stopping an Event Stream

There’s two ways to stop an event stream, depending on whether the client or the server initiates the termination.

Advanced — Dropped Connection & Recovery

As the HTTP connection that is used to send events to the client is open for a relatively long time, there’s a good chance that it may get dropped due to the network temporarily going away or the server deciding that it has been open long enough and terminating it. This may happen before the client has received all the events, in which case it may wish to reconnect and pick up from where it left off in the event stream.

The browser will automatically attempt to reconnect to an event source if the connection is dropped. When it does, it will send the ID of the last event that it received as HTTP header “Last-Event-ID” to the server in a new HTTP request. The server can then start sending events that have happened since the supplied ID, if that is possible for server-side logic to determine.

For more read @



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Anil Kumar

Anil Kumar

Experience with Front-end Technologies and MERN / MEAN Stack. Working on all Major UI Frameworks like React, Angular.