DEV Community

Jack Chipofya
Jack Chipofya

Posted on

Building a Socket.io Chat Application in Node.js

Welcome to this tutorial on coding a Socket.io chat server in Node.js! Socket.io is a popular library that enables real-time, bidirectional communication between clients and servers. In this tutorial, you'll learn how to build a simple chat server using Socket.io and Node.js.

We'll start by setting up the project and installing the necessary dependencies. Then, we'll create a server file where we'll handle the Socket.io connections and events. We'll also set up routes for serving the chat client HTML file. Next, we'll implement the chat functionality by listening for chat messages and broadcasting them to all connected clients.

Once the server is ready, we'll create a basic chat client HTML file where users can enter messages and see the received messages. Finally, we'll run the server and test the chat functionality by opening multiple browser tabs and exchanging messages in real-time.

By the end of this tutorial, you'll have a solid understanding of how to build a Socket.io chat server in Node.js. So let's get started with setting up the project!

Sure! Here's a step-by-step tutorial for coding a Socket.io chat server in Node.js:

Step 1: Set up the project

  1. Create a new directory for your project and navigate to it in your terminal.
  2. Initialize a new Node.js project by running the following command:
   npm init -y
Enter fullscreen mode Exit fullscreen mode
  1. Install the required dependencies by running the following command:
   npm install express socket.io
Enter fullscreen mode Exit fullscreen mode

Step 2: Create the server file

  1. Create a new file called server.js in your project directory.
  2. Open server.js and require the necessary modules at the top of the file:
   const express = require('express');
   const http = require('http');
   const socketIO = require('socket.io');
Enter fullscreen mode Exit fullscreen mode
  1. Create an instance of the Express application and create an HTTP server using http module:
   const app = express();
   const server = http.createServer(app);
Enter fullscreen mode Exit fullscreen mode
  1. Attach the Socket.io server to the HTTP server:
   const io = socketIO(server);
Enter fullscreen mode Exit fullscreen mode

Step 3: Set up the routes

  1. Define a route for serving the chat client HTML file:
   app.get('/', (req, res) => {
     res.sendFile(__dirname + '/index.html');
   });
Enter fullscreen mode Exit fullscreen mode

Step 4: Set up Socket.io event handling

  1. Add event handlers for Socket.io connections and disconnections:
   io.on('connection', (socket) => {
     console.log('A user connected');

     socket.on('disconnect', () => {
       console.log('A user disconnected');
     });
   });
Enter fullscreen mode Exit fullscreen mode

Step 5: Implement chat functionality

  1. Inside the connection event handler, listen for chat messages and broadcast them to all connected clients:
   socket.on('chat message', (message) => {
     console.log('Received message:', message);

     // Broadcast the message to all connected clients
     io.emit('chat message', message);
   });
Enter fullscreen mode Exit fullscreen mode

Step 6: Start the server

  1. Add a listener for incoming requests on a specified port:
   const port = 3000; // Choose any port number you prefer
   server.listen(port, () => {
     console.log(`Server listening on port ${port}`);
   });
Enter fullscreen mode Exit fullscreen mode

Step 7: Create the chat client HTML file

  1. Create a new file called index.html in your project directory.
  2. Open index.html and add the following content:
   <!DOCTYPE html>
   <html>
   <head>
     <title>Socket.io Chat</title>
   </head>
   <body>
     <ul id="messages"></ul>
     <form id="chat-form">
       <input id="message-input" autocomplete="off" />
       <button type="submit">Send</button>
     </form>

     <script src="/socket.io/socket.io.js"></script>
     <script>
       const socket = io();

       const form = document.getElementById('chat-form');
       const input = document.getElementById('message-input');
       const messages = document.getElementById('messages');

       form.addEventListener('submit', (e) => {
         e.preventDefault();
         const message = input.value;
         socket.emit('chat message', message);
         input.value = '';
       });

       socket.on('chat message', (message) => {
         const li = document.createElement('li');
         li.innerText = message;
         messages.appendChild(li);
       });
     </script>
   </body>
   </html>
Enter fullscreen mode Exit fullscreen mode

Step 8: Run the

server

  1. In your terminal, run the following command to start the server:
   node server.js
Enter fullscreen mode Exit fullscreen mode
  1. Open your web browser and navigate to http://localhost:3000 (or the port you specified).
  2. Open multiple browser tabs and test the chat functionality by sending messages.

Congratulations! You have successfully created a Socket.io chat server in Node.js. Users can now connect to the server and exchange chat messages in real-time. Feel free to customize and expand the functionality as per your requirements.

Top comments (0)