Mobile App Development

Building Real-time Chat Applications with Socket.io and Node.js

By the end of this guide, you'll have a basic understanding of how to set up a WebSocket server, handle events, and integrate the chat functionality with a front-end framework.

Mar 7, 2024 3 min read
Building Real-time Chat Applications with Socket.io and Node.js

This tutorial walks through building a real-time chat application using Socket.io and Node.js. Real-time chat lets users communicate instantly, which makes it a good fit for messaging platforms, collaborative tools, and similar products. By the end you'll know how to set up a WebSocket server, handle events, and wire the chat functionality into a front-end.

Prerequisites

Before we begin, make sure you have the following:

  1. Basic knowledge of JavaScript and Node.js.
  2. Node.js installed on your machine.
  3. A code editor such as Visual Studio Code or Sublime Text.

Setting Up the Project

Step 1: Initialize a new Node.js project

First, let's create a new directory for our project and initialize a new Node.js project using npm.

mkdir real-time-chat-app
cd real-time-chat-app
npm init -y

Step 2: Install dependencies

Next, install the necessary dependencies: Socket.io and Express.

npm install socket.io express

Creating the Server

Step 3: Setting up the WebSocket server

Now, let's create a server.js file and set up our WebSocket server using Socket.io.

// server.js
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);

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

server.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});

// Socket.io logic goes here

Handling Socket Events

Step 4: Handling connection and disconnection events

Socket.io provides built-in events for handling connection and disconnection of clients. Let's add logic to handle these events.

// server.js
io.on('connection', (socket) => {
  console.log('A user connected');

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

Implementing Chat Functionality

Step 5: Implementing chat messages

Now, let's implement the functionality to send and receive chat messages.

// server.js
io.on('connection', (socket) => {
  console.log('A user connected');

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

  socket.on('chat message', (message) => {
    console.log('message: ' + message);
    io.emit('chat message', message);
  });
});

Step 6: Integrating with the front-end

Finally, let's create a basic HTML file to serve as our front-end.

<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Real-time Chat</title>
</head>
<body>
  <ul id="messages"></ul>
  <form id="form" action="">
    <input id="input" autocomplete="off">
    <button>Send</button>
  </form>

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

    var form = document.getElementById('form');
    var input = document.getElementById('input');

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

    socket.on('chat message', function(msg) {
      var item = document.createElement('li');
      item.textContent = msg;
      document.getElementById('messages').appendChild(item);
    });
  </script>
</body>
</html>

Running the Application

Step 7: Run the server

Run the server using the following command:

node server.js

Open your web browser and navigate to http://localhost:3000. You should see the chat interface. Open multiple tabs or browsers to test real-time communication.

Conclusion

You now have a working real-time chat application built on Socket.io and Node.js. From here, the natural next steps are user authentication, private messaging, or message persistence in a database. Try swapping in a different front-end framework — the server-side code stays the same regardless of what renders the UI.

Real-time chat applicationsSocket.io tutorialSocket.io basicsBuilding chat apps with Node.js
Grow your business with us

Take your business to the next level.

Tell us what you're building. We'll come back inside one business day with a fixed scope, timeline, and team — or an honest “this isn't a fit”.

ENGINEERING PHILOSOPHY

Code is useless if it's not comprehensible to those who maintain it. We write code the next person can actually understand.