Home >Web Front-end >JS Tutorial >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.
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:
Create a new JS file named client.js in the public folder, and then add the following code:
const socket = io(); const messageList = document.getElementById('messages'); const messageForm = document.getElementById('chat-form'); const messageInput = document.getElementById('message'); messageForm.addEventListener('submit', function (e) { e.preventDefault(); socket.emit('chat message', messageInput.value); messageInput.value = ''; }); socket.on('chat message', function (msg) { const item = document.createElement('li'); item.textContent = msg; messageList.appendChild(item); window.scrollTo(0, document.body.scrollHeight); });
The above code is a simple client script that handles communication between the user interface and Socket.IO. The main responsibility of the client code is to send messages to the server and display the received messages on the user interface. We use the emit() method of Socket.IO to send messages to the server, and use the on() method to receive messages sent from the server.
Now that we have all the files ready, we can start the web server and test them in the browser. In the terminal, go to the project root directory and enter the following command:
node server.js
Enter http://localhost:3000/ in the browser to open the application. Enter some chat messages into the user interface and we can see them being added to the chat message list.
Node.js and Socket.IO are very good choices for developing web applications that implement instant messaging. In this article, we introduced how to create a web-based chat application that uses Node.js as the runtime environment, Express as the web framework, Socket.IO as the real-time communication engine, and MongoDB as the data storage. This is a very simple example, but it shows us how these technologies can be used to implement instant messaging capabilities.
The above is the detailed content of Web project using Node.js to implement instant messaging function. For more information, please follow other related articles on the PHP Chinese website!