Multiple Chat Rooms with Node and WebSockets

Multiple Chat Rooms with Node and WebSockets

ยท

3 min read

To extend your Node.js and Express chat application to support multiple chat rooms using WebSockets, you can use the socket.io library. Below is a step-by-step guide to help you implement this feature:

Step 1: Install Necessary Packages

Install the express and socket.io packages:

npm install express socket.io

Step 2: Set Up Your Project

Ensure you have your existing Node.js and Express chat application. If not, you can follow the steps to create a simple chat application.

Step 3: Modify Your Express Server

In your server.js or app.js file, set up socket.io in conjunction with your existing Express app:

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

// Serve static files (e.g., HTML, CSS, JavaScript)
app.use(express.static(__dirname + '/public'));

// Socket.IO connection handling
io.on('connection', (socket) => {
  console.log('A user connected');

  // Handle events related to real-time chat here

  socket.on('disconnect', () => {
    console.log('User disconnected');
  });
});

const PORT = process.env.PORT || 3000;

server.listen(PORT, () => {
  console.log(`Server is running on http://localhost:${PORT}`);
});

Step 4: Update Your Frontend

If your chat application has a frontend, update it to allow users to choose a chat room. Add a form or some UI elements to select or create a chat room.

<!-- public/index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Chat Application</title>
</head>
<body>

  <form id="roomForm">
    <label for="room">Choose a Chat Room:</label>
    <select id="room" name="room">
      <option value="general">General</option>
      <option value="programming">Programming</option>
      <option value="random">Random</option>
    </select>
    <button type="submit">Join Room</button>
  </form>

  <ul id="messages"></ul>

  <form id="messageForm">
    <input id="messageInput" autocomplete="off" /><button>Send</button>
  </form>

  <script src="https://cdn.socket.io/4.1.3/socket.io.min.js"></script>
  <script src="chat.js"></script>
</body>
</html>

Step 5: Handle Room Selection in the Server

Modify your server to handle room selection when a user connects:

// Socket.IO connection handling
io.on('connection', (socket) => {
  console.log('A user connected');

  // Handle events related to real-time chat here
  socket.on('join', (room) => {
    socket.join(room);
    console.log(`User joined room: ${room}`);
  });

  socket.on('message', (data) => {
    // Broadcast the message to everyone in the room
    io.to(data.room).emit('message', data);
  });

  socket.on('disconnect', () => {
    console.log('User disconnected');
  });
});

Step 6: Update Client-Side JavaScript

Update your client-side JavaScript (chat.js) to handle room selection and messaging:

// chat.js
const socket = io();

// Room selection
document.getElementById('roomForm').addEventListener('submit', (e) => {
  e.preventDefault();
  const room = document.getElementById('room').value;
  socket.emit('join', room);
});

// Message sending
document.getElementById('messageForm').addEventListener('submit', (e) => {
  e.preventDefault();
  const room = document.getElementById('room').value;
  const messageInput = document.getElementById('messageInput');
  const message = messageInput.value.trim();

  if (message) {
    socket.emit('message', { room, message });
    messageInput.value = '';
  }
});

// Display incoming messages
socket.on('message', (data) => {
  const messages = document.getElementById('messages');
  const li = document.createElement('li');
  li.textContent = `${data.room} - ${data.message}`;
  messages.appendChild(li);
});

Step 7: Test Your Multi-Room Chat Application

  1. Start your Express server.

     node server.js
    
  2. Open multiple browser tabs and connect to different chat rooms.

  3. Send messages within each room and observe that messages are only broadcasted to users in the same room.

Congratulations! You've successfully extended your chat application to support multiple chat rooms using WebSockets and the socket.io library. Customize and expand this implementation based on your specific requirements.

Did you find this article valuable?

Support Revive Coding by becoming a sponsor. Any amount is appreciated!

ย