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.
We will use the following technologies to develop this instant messaging function:
First create a project folder, enter the directory, and then execute the following commands:
npm init npm install express socket.io mongodb --save
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'); });
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.
Run the following command to install MongoDB:
npm install mongodb --save
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(); });
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.
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'); });
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.
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>
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: