Home > Web Front-end > JS Tutorial > body text

Web project using Node.js to implement instant messaging function

PHPz
Release: 2023-11-08 11:38:05
Original
667 people have browsed it

Web project using Node.js to implement instant messaging function

With the rapid development of the Internet, instant messaging functions are becoming more and more common. Whether it is social networks, e-commerce, online games, etc., instant messaging functions need to be implemented to improve user experience and efficiency. As an efficient JavaScript running environment suitable for concurrent requests, Node.js provides good support for quickly building web applications with instant messaging functions.

This article will introduce in detail how to use Node.js to implement a Web-based instant messaging function. This project is based on the WebSocket protocol and does not use traditional polling or long polling technology. The advantage of WebSocket technology is that it can realize real-time two-way communication between the server and the client, and it also has good support for cross-domain requests.

  1. Technology Selection

We will use the following technologies to develop this instant messaging function:

  • Node.js: We will use Node.js serves as the server-side operating environment.
  • Express: We will use the Express framework to develop web applications.
  • Socket.IO: Socket.IO is a cross-platform real-time communication engine based on WebSocket and polling. It is compatible with different browsers and mobile devices.
  • MongoDB: We will use MongoDB as data storage.
  • Bootstrap: We will use the Bootstrap framework to build the user interface.
  1. Build the project framework

First create a project folder, enter the directory, and then execute the following commands:

npm init
npm install express socket.io mongodb --save
Copy after login

The above The command will create a new Node.js project and then install the required dependencies.

The first step is to create a new JavaScript file in the project root directory. In this case, we named the file server.js. Then copy the code below into the server.js file.

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

// TODO:编写代码来启动Socket.IO服务

app.use(express.static('public'));

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

The above code introduces the Express framework, creates an HTTP server object, and listens to port 3000. This involves the initialization and startup of Socket.IO, which will be discussed later. At the same time, express.static() is used to set access to the program's static folder.

  1. Configuring MongoDB

Run the following command to install MongoDB:

npm install mongodb --save
Copy after login

Create a new one named mongo.js in the project root directory JS file and then add the following code to set up and run MongoDB.

const MongoClient = require('mongodb').MongoClient;

// Connection URL
const url = 'mongodb://localhost:27017';
// Database Name
const dbName = 'chatDB';
// Use connect method to connect to the server
MongoClient.connect(url, function (err, client) {
  console.log('Connected successfully to mongodb server');

  const db = client.db(dbName);
  client.close();
});
Copy after login

In this file, we use the MongoClient object officially provided by MongoDB to connect to the MongoDB server. MongoClient connects to the mongod instance using the URL and it performs the operation with dbName as parameter. After running mongo.js, if you see a message similar to "Successfully connected to MongoDB server", you have successfully connected to MongoDB.

  1. Start the Socket.IO service

In order to start the Socket.IO service, we will add the following code to the server.js file just now:

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

const io = require('socket.io')(http);
io.on('connection', function (socket) {
  console.log('a user connected');
  socket.on('disconnect', function () {
    console.log('user disconnected');
  });
});

app.use(express.static('public'));

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

The above code imports and creates an instance from the socket.io module, and then sets the connection event. The connection event is triggered when a client connects to a Socket.IO server. We've added some logging output to the connection events so that we can know on the server console how many users are connected to our Socket.IO server.

  1. Create Client

Now we will start creating the client. In the public folder, create a file called index.html and add the following code:

<!DOCTYPE html>
<html>
  <head>
    <title>Node.js Chat App</title>
  </head>
  <body>
    <h1>Welcome to the Chat Room!</h1>
    <div id="messages"></div>
    <form id="chat-form" action="#">
      <input id="message" type="text" placeholder="Type message" />
      <button type="submit">Send</button>
    </form>
    <script src="/socket.io/socket.io.js"></script>
    <script src="/client.js"></script>
  </body>
</html>
Copy after login

In the above code, we have created a simple user interface to send and Receive instant messages. The user interface mainly consists of three parts:

  • A
    element used to display chat messages.
  • A form that users can use to send messages.
  • Two
    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!