Home Web Front-end Front-end Q&A Build a chat room with nodejs

Build a chat room with nodejs

May 24, 2023 pm 12:23 PM

With the rapid development of the Internet, the way people communicate with each other is also constantly changing. Chat room is an online instant messaging application that allows users to communicate and exchange information in real time, regardless of geographical or time zone restrictions. There are many ways to implement chat rooms. This article will introduce how to build a chat room with nodejs.

1. The basic implementation principle of the chat room

The chat room is a network-based instant messaging system, and its implementation principle is very simple. When a user enters the chat room, the user needs to connect to the chat server first, and the server will add the user's connection information to the user list of the chat room. When a user sends a message to the chat room, the server broadcasts the message to all users in the chat room. In addition, the server also needs to monitor the user's connection status and disconnected user information in real time.

2. Preparation

Before you start building a chat room, make sure you have installed nodejs and npm. If not, you can go to the nodejs official website to download and install it.

3. Build the server side of the chat room

  1. Create the project

First, we need to create a chat room project in the local environment, and Download some necessary modules. First create a project directory on the command line and enter:

mkdir myChatRoom
cd myChatRoom
Copy after login

Then use npm to initialize the project:

npm init
Copy after login

Next install the modules you need to use:

npm i express socket.io -S
Copy after login

In the above command :

  • express is a commonly used nodejs web framework used to handle HTTP requests and responses.
  • socket.io is a real-time communication library based on websocket encapsulation.
  1. Server-side code implementation

In the project root directory, create the index.js file and paste the following code into:

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

app.use(express.static(__dirname + '/public'));

const onlineUsers = {};
const onlineCount = 0;

io.on('connection', (socket) => {
  console.log('a user connected');

  socket.on('login', (user) => {
    socket.nickname = user.username;
    // check if the user already exists
    if (!onlineUsers.hasOwnProperty(socket.nickname)) {
      onlineUsers[socket.nickname] = user.avatar;
      onlineCount++;
    }

    io.emit('login', { onlineUsers, onlineCount, user });
    console.log(`user ${user.username} joined`);
  });

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

  socket.on('disconnect', () => {
    if (onlineUsers.hasOwnProperty(socket.nickname)) {
      const userLeft = { username: socket.nickname, avatar: onlineUsers[socket.nickname] };
      delete onlineUsers[socket.nickname];
      onlineCount--;

      io.emit('logout', { onlineUsers, onlineCount, user: userLeft });
      console.log(`user ${userLeft.username} left`);
    }
  });
});

http.listen(3000, () => {
  console.log('listening on *:3000');
});
Copy after login

In the above code, we started an http server and upgraded the HTTP service using socket.io to support websocket. Then we can see that we have defined several socket events:

  1. When there is a new Socket connection, the server will send the connection event, and we will output "a user connected".
  2. When a user logs in, the server will send a login event and add the user's information to the online user list, and then the server will broadcast the online user list to other users.
  3. When a user sends a message, the server will send the chatMessage event and broadcast the message to all online users.
  4. When a user disconnects, the server will send a disconnect event and delete the user from the online user list.

4. Build a chat room client

  1. Create an html file

Create an html file in the public directory of the project, and Copy the following code into the file:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Chatroom</title>
    <style>
        #nickname {
            display: none;
        }

        #messages {
            height: 300px;
            overflow-y: scroll;
            margin-bottom: 10px;
        }

        ul {
            list-style: none;
            padding: 0;
            margin: 0;
        }

        li {
            margin-top: 10px;
        }

        img {
            width: 30px;
            height: 30px;
            vertical-align: middle;
            margin-right: 10px;
        }
    </style>
</head>
<body>
<div id="loginPanel">
    <p>输入一个昵称:</p>
    <input type="text" id="nicknameInput">
    <button id="submit">进入聊天室</button>
</div>
<div id="chatroom" style="display:none;">
    <div id="nickWrapper">
        <img id="avatarImg" src=""/>
        <span id="nickname"></span>
        <button id="logout">退出聊天室</button>
    </div>
    <div id="messages"></div>
    <input type="text" id="messageInput" placeholder="请输入聊天信息">
    <button id="sendBtn">发送</button>
</div>

<script src="./socket.io/socket.io.js"></script>
<script src="./chat.js"></script>
</body>
</html>
Copy after login

In the above code, we added a nickname input box to the HTML, a button to enter the chat room, a button to exit the chat room, and an ID with "messages" elements, an input box for sending messages and a button for sending messages. Among them, the nickname input box and the button to enter the chat room are hidden after entering the chat room, and the nickname and avatar of the online user are displayed.

  1. Create chat room client JS code

Create a chat.js file in the public directory and paste the following code into it:

const socket = io();
const submitBtn = document.querySelector('#submit');
const logoutBtn = document.querySelector('#logout');
const sendBtn = document.querySelector('#sendBtn');
const messageInput = document.querySelector('#messageInput');
const nicknameInput = document.querySelector('#nicknameInput');
const chatWrapper = document.querySelector('#chatroom');
const loginPanel = document.querySelector('#loginPanel');
const avatarImg = document.querySelector('#avatarImg');
const nickname = document.querySelector('#nickname');
const messages = document.querySelector('#messages');

let avatar;


// 提交昵称登录
submitBtn.addEventListener('click', function () {
  const nickname = nicknameInput.value;
  if (nickname.trim().length > 0) {
    avatar = `https://avatars.dicebear.com/api/bottts/${Date.now()}.svg`;
    socket.emit('login', { username: nickname, avatar: avatar });
  } else {
    alert('昵称为空,请重新输入');
    nicknameInput.value = '';
    nicknameInput.focus();
  }
});

// 退出登录
logoutBtn.addEventListener('click', function () {
  socket.disconnect();
});

// 发送消息
sendBtn.addEventListener('click', function () {
  const msg = messageInput.value.trim();
  if (msg.length > 0) {
    socket.emit('chatMessage', msg);
    messageInput.value = '';
    messageInput.focus();
  }
});

// 回车发送消息
messageInput.addEventListener('keyup', function (e) {
  e.preventDefault();
  if (e.keyCode === 13) {
    sendBtn.click();
  }
});

// 服务器发送登录信号
socket.on('login', (info) => {
  loginPanel.style.display = 'none';
  chatWrapper.style.display = 'block';
  avatarImg.src = avatar;
  nickname.innerText = nicknameInput.value;
  renderUserList(info.onlineUsers);
});

// 服务器发送聊天消息信号
socket.on('chatMessage', (data) => {
  renderChatMessage(data.nickname, data.message);
});

// 服务器发送退出信号
socket.on('logout', (info) => {
  renderUserList(info.onlineUsers);
});

// 渲染在线用户列表
function renderUserList(users) {
  const list = document.createElement('ul');
  Object.keys(users).forEach((nickname) => {
    const item = `
    <li>
      <img src="${users[nickname]}"/>
      <span>${nickname}</span>
    </li>
    `;
    list.innerHTML += item;
  });
  chatWrapper.insertBefore(list, messages);
}

// 渲染聊天消息
function renderChatMessage(nickname, message) {
  const msg = document.createElement('div');
  msg.innerHTML = `<p>${nickname}: ${message}</p>`;
  messages.appendChild(msg);
}
Copy after login

In the above code, we have implemented the following functions:

  1. When the user clicks the "Login" button, the "login" event is sent to the server, and the server is entrusted to add the user to "Online Users" internally. list, and push the current "online users" list to all clients through broadcast.
  2. When there is a chat message, the server will send the "chatMessage" event and push the content of the message to all clients through broadcast.
  3. When a user disconnects, the "Online User List" will delete the user from the user list and push the current "Online User" list to all clients through broadcast.

5. Run the project

Enter the project root directory on the command line and enter the following command to start the project:

node index.js
Copy after login

Then enter http in the browser ://localhost:3000/ Access the server and enter the chat room.

6. Summary

In this article, we implemented a simple chat room based on nodejs and socket.io, which provides a simple, stable and convenient way to build a chat room. efficient way. Although this is only a very basic chat room, I believe that readers can have a general understanding of building a chat room with nodejs through the introduction and practice of this article.

The above is the detailed content of Build a chat room with nodejs. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What is useEffect? How do you use it to perform side effects? What is useEffect? How do you use it to perform side effects? Mar 19, 2025 pm 03:58 PM

The article discusses useEffect in React, a hook for managing side effects like data fetching and DOM manipulation in functional components. It explains usage, common side effects, and cleanup to prevent issues like memory leaks.

Explain the concept of lazy loading. Explain the concept of lazy loading. Mar 13, 2025 pm 07:47 PM

Lazy loading delays loading of content until needed, improving web performance and user experience by reducing initial load times and server load.

How does the React reconciliation algorithm work? How does the React reconciliation algorithm work? Mar 18, 2025 pm 01:58 PM

The article explains React's reconciliation algorithm, which efficiently updates the DOM by comparing Virtual DOM trees. It discusses performance benefits, optimization techniques, and impacts on user experience.Character count: 159

How does currying work in JavaScript, and what are its benefits? How does currying work in JavaScript, and what are its benefits? Mar 18, 2025 pm 01:45 PM

The article discusses currying in JavaScript, a technique transforming multi-argument functions into single-argument function sequences. It explores currying's implementation, benefits like partial application, and practical uses, enhancing code read

What are higher-order functions in JavaScript, and how can they be used to write more concise and reusable code? What are higher-order functions in JavaScript, and how can they be used to write more concise and reusable code? Mar 18, 2025 pm 01:44 PM

Higher-order functions in JavaScript enhance code conciseness, reusability, modularity, and performance through abstraction, common patterns, and optimization techniques.

What is useContext? How do you use it to share state between components? What is useContext? How do you use it to share state between components? Mar 19, 2025 pm 03:59 PM

The article explains useContext in React, which simplifies state management by avoiding prop drilling. It discusses benefits like centralized state and performance improvements through reduced re-renders.

How do you connect React components to the Redux store using connect()? How do you connect React components to the Redux store using connect()? Mar 21, 2025 pm 06:23 PM

Article discusses connecting React components to Redux store using connect(), explaining mapStateToProps, mapDispatchToProps, and performance impacts.

How do you prevent default behavior in event handlers? How do you prevent default behavior in event handlers? Mar 19, 2025 pm 04:10 PM

Article discusses preventing default behavior in event handlers using preventDefault() method, its benefits like enhanced user experience, and potential issues like accessibility concerns.

See all articles