Real-time Chat Application Examples

Explore practical examples of real-time chat applications using WebSockets for seamless communication.
By Jamie

Introduction to Real-time Chat Applications Using WebSockets

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.

Example 1: Basic Chat Application

Context

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);
            }
        });
    });
});

Notes

  • This example uses Node.js and the ws library for WebSocket functionality.
  • To test the chat application, you can create multiple browser windows and connect to ws://localhost:8080.
  • For a more advanced version, consider adding user authentication and message history.

Example 2: Group Chat Application with User Management

Context

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);
    });
});

Notes

  • This implementation allows users to specify which room they want to send messages to, making it suitable for group chats.
  • Consider implementing features such as private messaging or room creation/deletion for additional functionality.

Example 3: Real-time Chat Application with Typing Indicator

Context

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);
});

Notes

  • In this example, when a user types in the input field, a typing indicator is sent to all connected clients.
  • You can enhance this further by showing the typing status in the chat UI, making it clear who is typing.

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.