WebSockets are a powerful technology that enables real-time communication between a client and a server. Unlike traditional HTTP requests, which are one-way and require a new connection for each request, WebSockets provide a persistent connection, allowing for continuous two-way interaction. This makes them an ideal choice for real-time chat applications, where instant messaging is crucial. Below are three diverse examples of real-time chat applications using WebSockets, each demonstrating different contexts and functionalities.
In this example, we will create a simple chat application that allows users to send and receive messages in real time. This application serves as a foundation for understanding the WebSocket protocol and basic messaging functionality.
// Server-side code using Node.js and WebSocket library
const WebSocket = require('ws');
const server = new WebSocket.Server({ port: 8080 });
server.on('connection', (socket) => {
socket.on('message', (message) => {
// Broadcast incoming message to all connected clients
server.clients.forEach((client) => {
if (client.readyState === WebSocket.OPEN) {
client.send(message);
}
});
});
});
ws
library for WebSocket functionality. ws://localhost:8080
. This example expands on the basic chat application by adding user management and group chat functionality. Users can join different chat rooms and see messages specific to their room, enhancing the chat experience.
// Server-side code with room management
const WebSocket = require('ws');
const server = new WebSocket.Server({ port: 8080 });
const rooms = {}; // Object to store rooms and their members
server.on('connection', (socket) => {
let currentRoom = 'general'; // Default room
if (!rooms[currentRoom]) rooms[currentRoom] = new Set();
rooms[currentRoom].add(socket);
socket.on('message', (message) => {
const { room, msg } = JSON.parse(message);
if (room) currentRoom = room; // Update room if specified
// Broadcast message to the current room
rooms[currentRoom].forEach((client) => {
if (client.readyState === WebSocket.OPEN) {
client.send(JSON.stringify({ room: currentRoom, msg }));
}
});
});
socket.on('close', () => {
rooms[currentRoom].delete(socket);
});
});
This example enhances the chat application by adding a typing indicator feature, which shows when users are actively typing a message. This feature improves user interaction and engagement in chat applications.
// Server-side code with typing indicator
const WebSocket = require('ws');
const server = new WebSocket.Server({ port: 8080 });
server.on('connection', (socket) => {
socket.on('message', (message) => {
const data = JSON.parse(message);
// Broadcast the message or typing indicator to all clients
server.clients.forEach((client) => {
if (client.readyState === WebSocket.OPEN) {
client.send(JSON.stringify(data));
}
});
});
});
// Client-side code for sending typing indication
const inputField = document.getElementById('chat-input');
inputField.addEventListener('input', () => {
const typingMessage = JSON.stringify({ type: 'typing', user: 'User1' });
socket.send(typingMessage);
});
These examples provide a solid foundation for building real-time chat applications using WebSockets. Each example can serve as a stepping stone to more advanced features, allowing developers to tailor their applications to specific user needs.