node.js 利用 socket.io 定时推送数据

node.js 利用 socket.io 定时推送数据


socket.io 是一种基于轮询、长连接、或 WebSocket 的双向通信 node.js 库,它能够自适应选用最合适的方法建立通信。

本文介绍一种在 node.js 服务端定时主动推送数据的方法。


1. 所需要的依赖库

node.js 轻量级框架 express、双向通信库 socket.io、定时任务工具 node-schedule


2. 代码实现

const config = require("./configure.js");  // 配置文件
const schedule = require("node-schedule");
const axios = require("axios").default;
const app = require("express")();
const server = require("http").createServer(app);
const io = require("socket.io")(server);

const ws = io.of(config.SOCKET_IO_NAMESPACE);  // 获取实例
let counter = 0;

ws.on("connection", function(socket) {  // 监听连接、断连事件
  counter += 1;
  console.log("the connection +1, now is", counter);

  socket.on("disconnect", function() {
    counter -= 1;
    console.log("the connection -1, now is", counter);
  });
});

// 定时推送任务
const bgPushTask = schedule.scheduleJob("*/2 * * * * *", async function() {
  if (counter > 0) {
    try {
      const res = await axios.get(config.RESTFUL_API_URI);
      ws.emit("push_data", res.data);  // 推送消息
      console.log("Push Data at", Date());
    } catch (error) {
      console.log(error);
    }
  }
});

server.listen(config.SERVER_PORT);

3. 相关链接


版权声明:本文为sigmarising原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。