Is the nodejs chat room easy to write?

WBOY
Release: 2023-05-11 19:38:05
Original
350 people have browsed it

Node.js Chat Room: Step by Step

Chat room is a very useful application in terms of real-time interaction and user experience. In modern web development technology, using Node.js can quickly build an efficient, real-time chat room, with excellent results. This article will explain the implementation of Node.js chat room, explore why it is so common and how to build it.

We need a programming language that both the server and the client can use, in this case, we consider using Node.js. Node.js has many advantages over other backend languages ​​like PHP or Java, the most important of which is that it is designed to be event-driven. This makes it better at handling large numbers of concurrent connections and allows fast processing of data in real-time applications.

Prerequisites

The first step in building a Node.js chat room is to install Node.js and npm (Node.js package manager). Open a terminal and enter the following command:

    $ sudo apt-get update
    $ sudo apt-get install nodejs
    $ sudo apt-get install npm
Copy after login

We will use npm to install the following 3 modules:

• socket.io: Makes web sockets easier to use.

• express: for web application development.

• nodemon: Used to monitor applications and restart them when changes occur.

Run the following command to install them:

    $ sudo npm install socket.io express nodemon
Copy after login

We are now ready to start building the chat room using Node.js.

1. Create Web Server

The first step in Node.js chat room is to create a Web Server to listen on the specified port, we can do this:

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

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

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

The code first creates an HTTP server using the express module, then creates a web socket server using the socket.io module, and finally sets the server to listen on port 3000 to run on the browser. The app.get() method is used to display the index.html file in the browser.

2. Open the connection on the client

The browser connects to the Web socket on the server, after two steps:

a. Reference the socket in HTML. io

Add the following two lines of code in the HTML file to be able to reference socket.io-client:

    
    
Copy after login

b. Open the connection on the client

Open a WebSocket connection so that the client can connect to the socket on the server. The code is as follows:

    const socket = io();
Copy after login

We will connect to the Node.js server and return an unfinalized WebSocket so that we can start sending and receiving messages through the socket.

  1. Implement sending messages to a certain room

Now our server is ready to receive connections between terminals. Next, we'll look at how to send messages to a specific room connection.

    socket.on('join', (room) => {
        socket.join(room);
    });

    socket.on('message', (msg, room) => {
        socket.to(room).emit('message', msg);
    });
Copy after login

In the code, we use the .join() method of the socket on the server to join the specified room. The server will do this when the client sends a 'join' message. The server then broadcasts the message to all users in the target room using the .to() method.

This can be done with the following command to send a message:

    socket.emit('message', 'Hello World', 'room1');
Copy after login
  1. Group Chat

The next step is to add a group chat to the server. The way we achieve this is:

    const users = {};

    socket.on('new-connection', () => {
        users[socket.id] = { name: `User ${Math.floor(Math.random() * 1000)}` };
        socket.broadcast.emit('user-connected', users[socket.id]);
    });

    socket.on('chat-message', (msg) => {
        socket.broadcast.emit('chat-message', { message: msg, name: users[socket.id].name });
    });

    socket.on('disconnect', () => {
        socket.broadcast.emit('user-disconnected', users[socket.id]);
        delete users[socket.id];
    });
Copy after login

First, we create a variable called "users" that will store every user connected to the server. When a user connects to the server, the object corresponding to it is stored in the "users" variable and a "user-connected" message is broadcast to all other users, which delivers the "users" variable with the new user.

When users send messages to the server, these messages are broadcast to all other users, including the original sender. When a user disconnects, the "user-disconnected" event is broadcast and the corresponding user is deleted from the "users" variable.

We are now ready to deploy the Node.js chat room. We can view the chat room in our local browser by running the following command:

    $ nodemon index.js
Copy after login

Conclusion

In this article, we have learned how to create a live chat using Node.js and socket.io app. We started by creating a web server and then saw how to open a connection on the client and send a message to a specific room. We've added a group chat feature that allows all users connected to the server to send messages to each other.

Node.js provides excellent tools and libraries that make it easier to implement real-time web functionality between the client and server side. Additionally, socket.io provides features that make it easier to handle. We hope this article helped you get started creating chat applications with Node.js!

The above is the detailed content of Is the nodejs chat room easy to write?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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 [email protected]
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!