Create Socket.io Realtime Chat App Node.js Step by Step for Dev

Tạo Socket.io Realtime Chat App Node.js Từng Bước Cho Dev

I remember when I used to create a forum for the class, having to F5 the page every 5 seconds to see if anyone was chatting or not, it was really tiring. Now with Node.js and Socket.io, building a smooth, F5-free real-time chat application is easier than ever. This article is my real-life experience at Pham Hai, will show you how to create a simple but fully functional Socket.io realtime chat app Node.js from scratch, guaranteed to be able to do it after reading it.

Final product and complete code for those who are "lazy" to read

Below is the entire source code of the real-time chat application. You just need to copy, paste and run and immediately have a finished product to tinker with.

Quick demo of what the chat application will look like

The app allows multiple users to connect, send messages, and instantly appear on everyone's screen without reloading the page.

The interface is extremely minimalist with a message display frame and an input box at the bottom. When a person types and clicks "Submit", that line of text bounces onto the screens of everyone who is visiting. This is the power of real-time communication. The feeling of coding this feature yourself for the first time is really "cool".

All server-side code (server.js file)

File server.js đảm nhiệm vai trò khởi tạo server, lắng nghe kết nối và xử lý logic phát sóng (broadcasting) tin nhắn.

I know many of you are looking for Socket.io chat app Node.js example code to try it out instead of reading lengthy theory. This is the most minimalist Node.js code combined with ExpressJS. If you're curious about how to use Express to do more complex things like writing APIs, you can take a look at my article Express.js creates a complete REST API.

const express = require('express');
const app = express();
const http = require('http');
const server = http.createServer(app);
const { Server } = require("socket.io");
const io = new Server(server);

app.get('/', (req, res) => {
  res.sendFile(__dirname + '/index.html');
});

io.on('connection', (socket) => {
  console.log('Một người dùng đã kết nối');

  socket.on('chat message', (msg) => {
    io.emit('chat message', msg);
  });

  socket.on('disconnect', () => {
    console.log('Người dùng đã ngắt kết nối');
  });
});

server.listen(3000, () => {
  console.log('Server đang chạy tại http://localhost:3000');
});

Entire client-side code (index.html file)

File index.html chứa cấu trúc HTML, CSS cơ bản và đoạn script JavaScript frontend để kết nối ngược lại server.

On the client-side side, we need an interface for users to interact with. The code below integrates the Socket.io client's CDN. This interface is not complicated, mainly focusing on the flow of sending and receiving data.

<!DOCTYPE html>
<html>
  <head>
    <title>Socket.io Chat App</title>
    <style>
      body { margin: 0; padding-bottom: 3rem; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; }
      #form { background: rgba(0, 0, 0, 0.15); padding: 0.25rem; position: fixed; bottom: 0; left: 0; right: 0; display: flex; height: 3rem; box-sizing: border-box; backdrop-filter: blur(10px); }
      #input { border: none; padding: 0 1rem; flex-grow: 1; border-radius: 2rem; margin: 0.25rem; }
      #input:focus { outline: none; }
      #form > button { background: #333; border: none; padding: 0 1rem; margin: 0.25rem; border-radius: 3px; outline: none; color: #fff; cursor: pointer; }
      #messages { list-style-type: none; margin: 0; padding: 0; }
      #messages > li { padding: 0.5rem 1rem; }
      #messages > li:nth-child(odd) { background: #efefef; }
    </style>
  </head>
  <body>
    <ul id="messages"></ul>
    <form id="form" action="">
      <input id="input" autocomplete="off" /><button>Gửi</button>
    </form>

    <script src="/socket.io/socket.io.js"></script>
    <script>
      var socket = io();
      var messages = document.getElementById('messages');
      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;
        messages.appendChild(item);
        window.scrollTo(0, document.body.scrollHeight);
      });
    </script>
  </body>
</html>

Instructions to run the application in 1 note

With just a few basic terminal commands, you can start the server and experience the results immediately.

Bạn tạo một thư mục trống, bỏ 2 file server.jsindex.html vào đó. Mở terminal lên, chạy npm init -y rồi gõ tiếp npm install express socket.io. Cuối cùng gõ node server.js. Mở trình duyệt truy cập vào Cổng http://localhost:3000 là xong. Dễ như ăn kẹo!

Let's get to work! Detailed step-by-step instructions

Below are step-by-step instructions for building a Socket.io Node.js chat application so you can clearly understand the nature of each line of code just copied above.

Step 1: Prepare the environment, install the necessary "tools".

Initialize the Node.js project and install required packages via npm.

Đầu tiên, bạn cần chắc chắn máy tính đã cài đặt Node.js. Đối với những bạn mới chuyển sang làm backend, việc nắm vững nền tảng là rất quan trọng. Bạn nên tham khảo bài viết Học Node.js từ đầu cho backend developer để củng cố kiến thức trước khi đi sâu hơn. Tiếp theo, mở terminal, tạo thư mục mới và chạy npm init -y để tạo file package.json. Sau đó, thực hiện cài đặt Socket.io và Node.js cho ứng dụng chat bằng lệnh: npm install express socket.io. Quá trình này sẽ tự động tải các thư viện cần thiết qua npm về máy của bạn.

Step 2: Build a simple Express server to serve HTML files

Use Express to create a basic web server, returning a chat interface to users when they access.

Trong file index.js (hoặc server.js tùy bạn đặt tên), mình gọi thư viện Express và tạo một HTTP server. Express sẽ lo việc routing. Cụ thể là khi người dùng vào trang chủ /, server sẽ gửi trả file index.html. Đây là mô hình client-server truyền thống cơ bản nhất mà bất kỳ web dev nào cũng phải nắm vững.

Step 3: Integrate Socket.io - "The heart" of the chat application

Attach Socket.io to the newly created HTTP server to start listening for WebSocket connections.

Chỗ này mới là phần "ăn tiền" nè. Mình khởi tạo một instance của Server từ thư viện socket.io và truyền cái HTTP server vào đó. Lúc này, ở server-side, Socket.io bắt đầu lắng nghe sự kiện connection. Mỗi khi có một tab trình duyệt mở trang web của bạn, một kết nối thời gian thực mới sẽ được thiết lập thành công.

Step 4: Handle the user interface and connection from the client

Write HTML/CSS code and use JavaScript to initiate a connection from the browser to the server.

Quay sang file index.html, bạn cần thêm thẻ <script src="/socket.io/socket.io.js"></script>. File script này được server Socket.io tự động cung cấp, bạn không cần phải tải thủ công. Sau đó, chỉ cần gọi biến const socket = io(); trong đoạn script là trình duyệt sẽ tự động tìm cách kết nối với server. Cách tạo ứng dụng chat realtime với Socket.io và Node.js thực chất bắt đầu từ dòng code nhỏ bé này.

Step 5: Send and receive real-time messages

Use the emit and on functions to transfer data back and forth between the client and server instantly.

When the user types a message and clicks submit, the client will use the socket.emit('chat message', msg) function to shoot data to the server. In the opposite direction, the server listens with socket.on('chat message', …). Receiving the message, the server immediately uses io.emit('chat message', msg) to broadcast the message to all connected people. This is the core of event-driven communication, which helps applications respond immediately.

Riddle for newbies: What is Socket.io and why is it so "divine"?

Socket.io is a JavaScript library that supports two-way, real-time, and event-based communication between the browser and the server.

"Painful" history: From Ajax Polling to Long-Polling

Before modern technology, programmers had to use resource-consuming tricks to simulate real time.

In the past, to use the chat function, we often used the Ajax Polling technique (every 3-5 seconds sending a request to the server to see if there was any new news). This method is extremely bandwidth intensive and slows down the server. A little more advanced, there is Long polling, the client sends a request, the server "soaks" that request until there is new data then returns it. Even though it's better, it's still quite bulky.

WebSocket was born and Socket.io is the "hero"

WebSocket provides a persistent connection channel, and Socket.io wraps it up to make it easier to use on all browser platforms.

Then the WebSocket protocol was born, allowing the opening of a continuous two-way connection pipe. However, coding pure WebSocket is quite extreme and error-prone. So Socket.io tutorial Node.js Vietnamese articles sprouted up like mushrooms because this library is so convenient. It automatically fallsback to Long-polling if the user's browser is too old to support WebSocket. To understand what Socket.io is and how it works in chat app, just imagine it as a perfect layer of armor that protects and strengthens WebSocket.

Quick comparison: Socket.io vs. Pure WebSocket

Socket.io offers many built-in features such as automatic reconnection and chat room sharing, while pure WebSocket is lighter but requires many things to be coded by hand.

Below is a quick comparison table based on my actual experience:

Criteria Pure WebSocket Socket.io
Bản chất HTML5 protocol standard Wrapper library (Wrapper)
Tự động kết nối lại No (Must write the logic yourself) Available, extremely stable
Chia phòng (Rooms) Self-manage complex logic Available API support, extremely easy to use

Upgrade the application: Add some more "pro" features

A real chat application needs more than just sending and receiving messages. Below are some suggestions for you to expand your project.

Display the message "Someone is typing..."

Catch the keypress event on the input box to notify others that someone is about to send a message.

Để xây dựng ứng dụng chat thời gian thực Node.js Socket.io xịn xò và giống thật hơn, bạn có thể bắt sự kiện input trên ô nhập liệu. Khi người dùng bắt đầu gõ, client sẽ emit một sự kiện tên là typing. Server nhận được sẽ broadcast sự kiện này cho các client khác (trừ người đang gõ) để hiển thị dòng chữ mờ mờ "Ai đó đang gõ…".

Displays a list of users currently online

Stores a list of connecting IDs to count the number of online users in the room.

When learninghow to create a multi-user chat application with Socket.io, knowing who is online is a must-have feature. You can save user IDs in an array or Set on the server. When someone connects or disconnects, the server will automatically update this array and send the latest list to everyone. This feature plays a fundamental role when you want to develop a multi-topic chat room system.

Send a message to a specific user (Private Message)

Send messages directly to a single socket.id instead of broadcasting to the entire system.

Thay vì dùng io.emit để gửi cho tất cả, bạn có thể dùng io.to(socketId).emit(...) để gửi tin nhắn riêng tư. Tuy nhiên, trong môi trường thực tế, để làm chức năng này an toàn và không bị lộ thông tin, bạn bắt buộc phải có hệ thống xác thực. Mình khuyên bạn nên áp dụng kiến thức từ bài JWT authentication Node.js bảo mật API để định danh chính xác ai đang chat với ai, từ đó hệ thống mới biết đường gửi tin nhắn đến đúng người nhận.

So you have built a Socket.io realtime chat app Node.js yourself. Looking back at the whole process, it's not too complicated, right? At Pham Hai, we realize that technology is always changing every day, but the core knowledge of real-time connectivity like this will always be a solid foundation. From this basic framework, you can completely confidently develop many other cool features. Wishing you success on your coding journey and creating great applications!

Have you tested the source code successfully? Please leave a comment below to show off your results. If you encounter any errors during the installation process or have problems with any lines of code, don't hesitate to ask, I will help answer as soon as possible!

Lưu ý: Các thông tin trong bài viết này chỉ mang tính chất tham khảo. Để có lời khuyên tốt nhất, vui lòng liên hệ trực tiếp với chúng tôi để được tư vấn cụ thể dựa trên nhu cầu thực tế của bạn.

Categories: Lập Trình Web Node.js

mrhai

Để lại bình luận