Communication between Client & Server

📄 Table of Contents

Websocket:

Session:

Update:

◉ JavaScript Session

Key Points

Window.sessionStorage

// 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();

◉ AJAX (Asynchronous Javascript and XML)

◉ WebSocket (inbuilt in HTML5)

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

// Inform the user about the error.
var label = document.getElementById("status-label");
label.innerHTML = "Error: " + event;
}
WebSocket.send("Hello server!");
WebSocket.send(JSON.stringify(obj));

◉ WebSocket vs. Long polling HTTP

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

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

Conclusion

Server Side Events (SSE)

Architecture

Flow of events between Client and Server

Message Format

Client (Browser) Implementation

Server Side Implementation

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

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