Home > Web Front-end > JS Tutorial > How to implement websocket communication function in nodejs

How to implement websocket communication function in nodejs

亚连
Release: 2018-06-12 11:54:19
Original
1556 people have browsed it

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

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"
 }
}
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 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(&#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 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
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 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!

source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template