Node.js WebSocket and Real-Time Communication:
Introduction to WebSocket Protocol:
What is WebSocket? is a communication protocol that provides full-duplex communication channels over a single TCP connection.
One single TCP connection allows two-way communication channels via the communication protocol of WebSocket.
It is a browser-to-server implementation that allows for less loading while enabling real-time communication between clients and servers.
Key Features of WebSocket:
- Two-way messaging: A single message can be sent by both the client and server simultaneously.
- Persistent Connection: No need to keep re-handshaking if a connection is not closed once made.
- Low Latency: Instead of opening a new HTTP connection for every request-response cycle, this reduces latency by preventing them from happening again.
Light-weight Headers: Communication using WebSocket has smaller headers relative to those in HTTP.
WebSocket Handshake:
The handshake begins with an HTTP request; later, it is transformed into a WebSocket connection.
Hence, when sending the message, the client utilizes unique HTTP requests for signaling the server.
Example of WebSocket handshake:
Client Request:
GET /chat HTTP/1.1
Host: server.example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw==
Sec-WebSocket-Protocol: chat, superchat
Sec-WebSocket-Version: 13
Server Response:
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: HSmrc0sMlYUkAGmm5OPpG2HaGWk=
Sec-WebSocket-Protocol: chat
Implementing Real-Time Communication Using Socket.io:
Socket.io is common framework that makes it easy to have WebSocket-based real-time communication between a user’s browser and a server, even if there is no support for WebSocket on the end-user web browsers.
Setting Up Socket.io:
- Installation:
- Install Socket.io for both the server and client.
npm install socket.io
npm install socket.io-client
- Server Implementation:
- Set up a basic Express server with Socket.io.
const express = require('express');
const http = require('http');
const socketIo = require('socket.io');
const app = express();
const server = http.createServer(app);
const io = socketIo(server);
io.on('connection', (socket) => {
console.log('New client connected');
// Handling a custom event from the client
socket.on('message', (data) => {
console.log('Message received:', data);
// Broadcast the message to all connected clients
io.emit('message', data);
});
// Handling client disconnection
socket.on('disconnect', () => {
console.log('Client disconnected');
});
});
const port = 3000;
server.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});
- Client Implementation:
- Create a basic HTML file to connect to the Socket.io server and handle real-time communication.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Socket.io Chat</title>
<script src="/socket.io/socket.io.js"></script>
</head>
<body>
<h1>Socket.io Chat</h1>
<input id="messageInput" type="text" placeholder="Type a message">
<button onclick="sendMessage()">Send</button>
<ul id="messages"></ul>
<script>
const socket = io();
// Function to send a message
function sendMessage() {
const input = document.getElementById('messageInput');
const message = input.value;
socket.emit('message', message);
input.value = '';
}
// Handling incoming messages
socket.on('message', (data) => {
const messages = document.getElementById('messages');
const messageElement = document.createElement('li');
messageElement.textContent = data;
messages.appendChild(messageElement);
});
</script>
</body>
</html>