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.

Websocket:

Session:

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.

Update:

◉ JavaScript Session

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 stores the data only till the browser is active.
  • Session is stored using session.Storage object.

Window.sessionStorage

  • 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, http://example.com will have separate storage than https://example.com.

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

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

// Remove saved data from sessionStorage
sessionStorage.removeItem('key');

// Remove all saved data from sessionStorage
sessionStorage.clear();

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)

  • 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)

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.send(JSON.stringify(obj));

◉ WebSocket vs. Long polling HTTP

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):

  • 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)

  • Cons: more complex and more server resources used. Example (ItsNat based)

Conclusion

  • 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)

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.

Architecture

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

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

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

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(() => {
response.write(
`event: myEvent\nid: ${id}\ndata:This is event ${id}.`
);
response.write('\n\n');
id++;
}, 3000);
}).listen(5000);

Stopping an Event Stream

Advanced — Dropped Connection & Recovery

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 @ https://medium.com/conectric-networks/a-look-at-server-sent-events-54a77f8d6ff7

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

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