


nodejs combines socket.io to implement websocket communication function
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 who need it can refer to it. I hope it can help. to everyone.
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, 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, which are used to store the socket server. read data.
Create a new public directory and create a new file index.html in it. The file content 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 we created two index.html files just now is to easily use 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 provided by nginx through chrome Service:
http://hostname/public/index.html
Turn on the developer mode, you can see in the console that the data collected every second The socket push message from the node server is received. 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.
Related recommendations:
WebSocket communication in Html5
Client communication function code implemented by ThinkPHP combined with ajax and Mysql Example
Introduction to the storage event of the communication method between js pages
The above is the detailed content of nodejs combines socket.io to implement websocket communication function. 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

AI Hentai Generator
Generate AI Hentai for free.

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

With the continuous development of Internet technology, real-time video streaming has become an important application in the Internet field. To achieve real-time video streaming, the key technologies include WebSocket and Java. This article will introduce how to use WebSocket and Java to implement real-time video streaming playback, and provide relevant code examples. 1. What is WebSocket? WebSocket is a protocol for full-duplex communication on a single TCP connection. It is used on the Web

With the continuous development of Internet technology, real-time communication has become an indispensable part of daily life. Efficient, low-latency real-time communication can be achieved using WebSockets technology, and PHP, as one of the most widely used development languages in the Internet field, also provides corresponding WebSocket support. This article will introduce how to use PHP and WebSocket to achieve real-time communication, and provide specific code examples. 1. What is WebSocket? WebSocket is a single

PHP and WebSocket: Best Practice Methods for Real-Time Data Transfer Introduction: In web application development, real-time data transfer is a very important technical requirement. The traditional HTTP protocol is a request-response model protocol and cannot effectively achieve real-time data transmission. In order to meet the needs of real-time data transmission, the WebSocket protocol came into being. WebSocket is a full-duplex communication protocol that provides a way to communicate full-duplex over a single TCP connection. Compared to H

In this article, we will compare Server Sent Events (SSE) and WebSockets, both of which are reliable methods for delivering data. We will analyze them in eight aspects, including communication direction, underlying protocol, security, ease of use, performance, message structure, ease of use, and testing tools. A comparison of these aspects is summarized as follows: Category Server Sent Event (SSE) WebSocket Communication Direction Unidirectional Bidirectional Underlying Protocol HTTP WebSocket Protocol Security Same as HTTP Existing security vulnerabilities Ease of use Setup Simple setup Complex performance Fast message sending speed Affected by message processing and connection management Message structure Plain text or binary Ease of use Widely available Helpful for WebSocket integration

Golang is a powerful programming language, and its use in WebSocket programming is increasingly valued by developers. WebSocket is a TCP-based protocol that allows two-way communication between client and server. In this article, we will introduce how to use Golang to write an efficient WebSocket server that handles multiple concurrent connections at the same time. Before introducing the techniques, let's first learn what WebSocket is. Introduction to WebSocketWeb

How does JavaWebsocket implement online whiteboard function? In the modern Internet era, people are paying more and more attention to the experience of real-time collaboration and interaction. Online whiteboard is a function implemented based on Websocket. It enables multiple users to collaborate in real-time to edit the same drawing board and complete operations such as drawing and annotation. It provides a convenient solution for online education, remote meetings, team collaboration and other scenarios. 1. Technical background WebSocket is a new protocol provided by HTML5. It implements

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use WebSocket for file transfer in golang WebSocket is a network protocol that supports two-way communication and can establish a persistent connection between the browser and the server. In golang, we can use the third-party library gorilla/websocket to implement WebSocket functionality. This article will introduce how to use golang and gorilla/websocket libraries for file transfer. First, we need to install gorilla
