Home  >  Article  >  Web Front-end  >  Build a chat room with nodejs

Build a chat room with nodejs

WBOY
WBOYOriginal
2023-05-24 12:23:38946browse

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

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.
  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');
});

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>

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);
}

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

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:
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