Back to Tutorials

Building a Real-time Chat Application with Socket.io

Introduction

Learn how to build a real-time chat application using Socket.io, a library that enables real-time, bidirectional communication between web clients and servers.

Server Setup

const express = require('express');
const http = require('http');
const { Server } = require('socket.io');

const app = express();
const server = http.createServer(app);
const io = new Server(server, {
  cors: { origin: 'http://localhost:3000' }
});

const users = new Map();

io.on('connection', (socket) => {
  socket.on('join', (username) => {
    users.set(socket.id, username);
    socket.broadcast.emit('user-joined', username);
  });

  socket.on('message', (data) => {
    io.emit('message', {
      username: users.get(socket.id),
      message: data.message,
      timestamp: new Date()
    });
  });

  socket.on('disconnect', () => {
    const username = users.get(socket.id);
    users.delete(socket.id);
    socket.broadcast.emit('user-left', username);
  });
});

server.listen(3001, () => {
  console.log('Server running on port 3001');
});

Client Implementation

import { io } from 'socket.io-client';

const socket = io('http://localhost:3001');
socket.emit('join', username);

socket.on('message', (data) => {
  displayMessage(data.username, data.message);
});

function sendMessage(message) {
  socket.emit('message', { message });
}

Features to Add

  • Private messaging
  • File sharing
  • Message history
  • User authentication
  • Room/channel support