Home Web Front-end JS Tutorial nodejs combines socket.io to implement websocket communication function

nodejs combines socket.io to implement websocket communication function

Jan 15, 2018 am 09:17 AM
javascript socket.io websocket

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
Copy after login

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"
 }
}
Copy after login

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(&#39;./data/trends.json&#39;,&#39;utf-8&#39;);#trends数据
  var coins = fs.readFileSync(&#39;./data/coins.json&#39;,&#39;utf-8&#39;);#coins数据
  #向所有socket连接发送数据
  for (i in iolist) {
    # 向客户端发送trends数据
    iolist[i].emit(&#39;trends&#39;, trends);
    # 向客户端发送coins数据
    iolist[i].emit(&#39;coins&#39;, coins);
  }
}, 1000);
# 服务器侦听在sockettest.com的3000端口上
http.listen(3000, function(){
  # 输出到标准输出
  console.log(&#39;listening on sockettest.com:3000&#39;);
});
Copy after login

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(&#39;http://sockettest.com:3000&#39;);
    socketdata(socket);
    function socketdata() {
      #定义接收到coins类型数据时的行为
      socket.on(&#39;coins&#39;, function(msg){
        console.log(msg);
      }
      #定义接收到trends类型数据时的行为
      socket.on(&#39;trends&#39;, function(msg){
        console.log(msg);
      }
    }
</script>
Copy after login

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
Copy after login

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!

Statement of this Website
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

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

The combination of Java and WebSocket: how to achieve real-time video streaming The combination of Java and WebSocket: how to achieve real-time video streaming Dec 17, 2023 pm 05:50 PM

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

How to achieve real-time communication using PHP and WebSocket How to achieve real-time communication using PHP and WebSocket Dec 17, 2023 pm 10:24 PM

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 practices for real-time data transfer PHP and WebSocket: Best practices for real-time data transfer Dec 18, 2023 pm 02:10 PM

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

SSE and WebSocket SSE and WebSocket Apr 17, 2024 pm 02:18 PM

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 WebSocket programming tips: handling concurrent connections golang WebSocket programming tips: handling concurrent connections Dec 18, 2023 am 10:54 AM

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 Java Websocket implement online whiteboard function? How does Java Websocket implement online whiteboard function? Dec 17, 2023 pm 10:58 PM

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 implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

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 How to use WebSocket for file transfer in golang Dec 18, 2023 am 09:06 AM

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

See all articles