search
HomeWeb Front-endJS TutorialWeb project using Node.js to implement instant messaging function

Web project using Node.js to implement instant messaging function

Nov 08, 2023 am 11:38 AM
nodejsinstant messagingweb project

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

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.

  1. Configuring MongoDB

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.

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

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 id="Welcome-to-the-Chat-Room">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:

  • A
    element used to display chat messages.
  • A form that users can use to send messages.
  • Two <script> elements. One is used to load the socket.io client library and the other is used to load the client script. </script>
    1. Implementing client script

    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.

    1. Testing the Application

    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.

    1. Conclusion

    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!

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
From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor