How to implement websocket communication function in nodejs
This article mainly introduces the method of nodejs combined with socket.io to realize websocket communication function. It analyzes the specific steps and related operation skills of nodejs combined with socket.io to realize websocket communication in the form of examples. Friends in need can refer to it
The example of this article describes the method of nodejs combined with socket.io to implement websocket communication function. Share it with everyone for your reference, the details are as follows:
Because there are scenarios in the project that require real-time acquisition of background data, the http heartbeat request method has been used before. Because websocket has a great performance improvement compared to this mode and can improve real-time performance, some research has been done on websocket. This is implemented using nodejs socket.io.
Achieve the goal
Change the original method of heartbeat request for background data to a unified push method through socket connection to the background. The background data is written to files or redis by other processes. What is implemented here is the way to read files.
Preliminary preparation
Installing nodejs (omitted)
Server side
Create a new project directory, here is sockettest
Enter the sockettest directory, install the express module and socketio module
npm install --save express@4.10.2 npm install --save socket.io
Create a new package.json file, and write the following content in it:
{ "name": "socket-test", "version": "0.0.1", "description": "my first socket.io app", "dependencies": { "express": "^4.10.2", "socket.io": "^1.7.2" } }
Create a new index.html, which is used as the default access display page, because it will not be used here, and the content is arbitrary;
Create a new trends.js file and write the content in it:
var app = require('express')(); var http = require('http').Server(app); var io = require('socket.io')(http); var fs = require('fs'); #默认打开文件 app.get('/', function(req, res){ res.sendfile('index.html'); }); #用于存储所有socket以广播数据 var iolist = []; #定义socket on connection(连入)事件行为 io.on('connection', function(socket){ #将连入socket加入列表 iolist.push(socket); #记录index,在disconnect(断开连接)发生时将对应的socket删除 var sockex = iolist.indexOf(socket); #定义on disconnect事件行为 socket.on('disconnect', function(){ #将断开连接的socket从广播列表里删除 iolist.splice(sockex, 1); }); }); # 数据广播进程:每1秒钟广播一次 setInterval(function() { # 如果没有正在连接的socket,直接返回; if (iolist.length <= 0) return; var trends = fs.readFileSync('./data/trends.json','utf-8');#trends数据 var coins = fs.readFileSync('./data/coins.json','utf-8');#coins数据 #向所有socket连接发送数据 for (i in iolist) { # 向客户端发送trends数据 iolist[i].emit('trends', trends); # 向客户端发送coins数据 iolist[i].emit('coins', coins); } }, 1000); # 服务器侦听在sockettest.com的3000端口上 http.listen(3000, function(){ # 输出到标准输出 console.log('listening on sockettest.com:3000'); });
Create a new data directory, and create two new files trends and coins below to store the data to be read by the socket server.
Create a new public directory and create a new file index.html in it. The content of the file is as follows:
<!--引入必要的js文件--> <script type="text/javascript" src="http://sockettest:3000/socket.io/socket.io.js"></script> <script type="text/javascript"> //新建socket var socket = io('http://sockettest.com:3000'); socketdata(socket); function socketdata() { #定义接收到coins类型数据时的行为 socket.on('coins', function(msg){ console.log(msg); } #定义接收到trends类型数据时的行为 socket.on('trends', function(msg){ console.log(msg); } } </script>
Code deployment
The reason why just now Two index.html files are created to facilitate the use of the socket service provided by nodejs in existing web projects. In this way, we can deploy public/index.html in other servers, such as nginx or tomcat, and then start the socket server in the root directory to provide socket services.
First execute
node ./trends.js
in the root directory of the project and keep the terminal running, then deploy the project in nginx and access the web services provided by nginx through chrome:
http://hostname/public/index.html
Turn on the developer mode, and you can see in the console that you will receive socket push messages from the node server every second. . By modifying the two files in the data directory, you can see that the data written to the files will also be pushed to the client in real time.
The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.
Related articles:
How to use cli in vue to reconstruct multi-page scaffolding
Realize click-down menu content in JS Synchronous input box
Realize input box and drop-down box linkage
Using parcel.js packaging error
Detailed interpretation of vue reconstruction technology
The above is the detailed content of How to implement websocket communication function in nodejs. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Node.js can be used as a backend framework as it offers features such as high performance, scalability, cross-platform support, rich ecosystem, and ease of development.

To connect to a MySQL database, you need to follow these steps: Install the mysql2 driver. Use mysql2.createConnection() to create a connection object that contains the host address, port, username, password, and database name. Use connection.query() to perform queries. Finally use connection.end() to end the connection.

The following global variables exist in Node.js: Global object: global Core module: process, console, require Runtime environment variables: __dirname, __filename, __line, __column Constants: undefined, null, NaN, Infinity, -Infinity

There are two npm-related files in the Node.js installation directory: npm and npm.cmd. The differences are as follows: different extensions: npm is an executable file, and npm.cmd is a command window shortcut. Windows users: npm.cmd can be used from the command prompt, npm can only be run from the command line. Compatibility: npm.cmd is specific to Windows systems, npm is available cross-platform. Usage recommendations: Windows users use npm.cmd, other operating systems use npm.

The main differences between Node.js and Java are design and features: Event-driven vs. thread-driven: Node.js is event-driven and Java is thread-driven. Single-threaded vs. multi-threaded: Node.js uses a single-threaded event loop, and Java uses a multi-threaded architecture. Runtime environment: Node.js runs on the V8 JavaScript engine, while Java runs on the JVM. Syntax: Node.js uses JavaScript syntax, while Java uses Java syntax. Purpose: Node.js is suitable for I/O-intensive tasks, while Java is suitable for large enterprise applications.

Original title: "How does a wireless mouse become wireless?" 》Wireless mice have gradually become a standard feature of today’s office computers. From now on, we no longer have to drag long cords around. But, how does a wireless mouse work? Today we will learn about the development history of the No.1 wireless mouse. Did you know that the wireless mouse is now 40 years old? In 1984, Logitech developed the world's first wireless mouse, but this wireless mouse used infrared as a The signal carrier is said to look like the picture below, but later failed due to performance reasons. It was not until ten years later in 1994 that Logitech finally successfully developed a wireless mouse that works at 27MHz. This 27MHz frequency also became the wireless mouse for a long time.

Yes, Node.js is a backend development language. It is used for back-end development, including handling server-side business logic, managing database connections, and providing APIs.

Node.js and Java each have their pros and cons in web development, and the choice depends on project requirements. Node.js excels in real-time applications, rapid development, and microservices architecture, while Java excels in enterprise-grade support, performance, and security.
