Home > Web Front-end > JS Tutorial > body text

nodejs combines socket.io to implement websocket communication function

小云云
Release: 2018-01-15 09:17:41
Original
1705 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 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!

Related labels:
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!