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!

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 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.

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'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.

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 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 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 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.


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

Dreamweaver Mac version
Visual web development tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software