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
- 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
Then use npm to initialize the project:
npm init
Next install the modules you need to use:
npm i express socket.io -S
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.
- 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'); });
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:
- When there is a new Socket connection, the server will send the connection event, and we will output "a user connected".
- 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.
- When a user sends a message, the server will send the chatMessage event and broadcast the message to all online users.
- 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
- 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 src="/static/imghwm/default1.png" data-src="./socket.io/socket.io.js" class="lazy" id="avatarImg"/ alt="Build a chat room with nodejs" > <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></script> <script src="./chat.js"></script> </body> </html>
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.
- 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="/static/imghwm/default1.png" data-src="${users[nickname]}" class="lazy"/ alt="Build a chat room with nodejs" > <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); }
In the above code, we have implemented the following functions:
- 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.
- 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.
- 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
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!

React is the tool of choice for building dynamic and interactive user interfaces. 1) Componentization and JSX make UI splitting and reusing simple. 2) State management is implemented through the useState hook to trigger UI updates. 3) The event processing mechanism responds to user interaction and improves user experience.

React is a front-end framework for building user interfaces; a back-end framework is used to build server-side applications. React provides componentized and efficient UI updates, and the backend framework provides a complete backend service solution. When choosing a technology stack, project requirements, team skills, and scalability should be considered.

The relationship between HTML and React is the core of front-end development, and they jointly build the user interface of modern web applications. 1) HTML defines the content structure and semantics, and React builds a dynamic interface through componentization. 2) React components use JSX syntax to embed HTML to achieve intelligent rendering. 3) Component life cycle manages HTML rendering and updates dynamically according to state and attributes. 4) Use components to optimize HTML structure and improve maintainability. 5) Performance optimization includes avoiding unnecessary rendering, using key attributes, and keeping the component single responsibility.

React is the preferred tool for building interactive front-end experiences. 1) React simplifies UI development through componentization and virtual DOM. 2) Components are divided into function components and class components. Function components are simpler and class components provide more life cycle methods. 3) The working principle of React relies on virtual DOM and reconciliation algorithm to improve performance. 4) State management uses useState or this.state, and life cycle methods such as componentDidMount are used for specific logic. 5) Basic usage includes creating components and managing state, and advanced usage involves custom hooks and performance optimization. 6) Common errors include improper status updates and performance issues, debugging skills include using ReactDevTools and Excellent

React is a JavaScript library for building user interfaces, with its core components and state management. 1) Simplify UI development through componentization and state management. 2) The working principle includes reconciliation and rendering, and optimization can be implemented through React.memo and useMemo. 3) The basic usage is to create and render components, and the advanced usage includes using Hooks and ContextAPI. 4) Common errors such as improper status update, you can use ReactDevTools to debug. 5) Performance optimization includes using React.memo, virtualization lists and CodeSplitting, and keeping code readable and maintainable is best practice.

React combines JSX and HTML to improve user experience. 1) JSX embeds HTML to make development more intuitive. 2) The virtual DOM mechanism optimizes performance and reduces DOM operations. 3) Component-based management UI to improve maintainability. 4) State management and event processing enhance interactivity.

React components can be defined by functions or classes, encapsulating UI logic and accepting input data through props. 1) Define components: Use functions or classes to return React elements. 2) Rendering component: React calls render method or executes function component. 3) Multiplexing components: pass data through props to build a complex UI. The lifecycle approach of components allows logic to be executed at different stages, improving development efficiency and code maintainability.

React Strict Mode is a development tool that highlights potential issues in React applications by activating additional checks and warnings. It helps identify legacy code, unsafe lifecycles, and side effects, encouraging modern React practices.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment