如何使用www.example.com和nodejs有效地处理投标站点socket.io,同时降低服务器负载

kknvjkwl  于 2023-01-08  发布在  Node.js
关注(0)|答案(1)|浏览(96)
    • bounty将在4天后过期**。回答此问题可获得+50的声誉奖励。Ajith正在寻找来自声誉良好来源的答案

In one of my website I need to show top 6 bidding products on one of the pages, where the top bid values should update without loading the page. I need to acheive this using nodejs socket.io, hoping that data would brodcast to multiple active users that are landed on that page , may be like in a time interval of 5 minutes. I prefer socket since I can reduce database load by broadcasting data in each 5 mins for multiple users, But I have some confusions, like if it is working correctly
我在下面添加了服务器端和客户端代码示例,
Nodejs Socket.io server side code.

let openConn = []; // For storing User sockets and product Id's on top bidding page

  io.on('connection', async function(socket) {

    openConn.push({socketId: socket.id, products : [] });
    socket.on("userInit",data=>{
        objIndex = openConn.findIndex((obj => obj.socketId == socket.id));
        if(typeof openConn[objIndex] !== "undefined")
          openConn[objIndex].data = data.data;
    })

    //Sample Data in openConnection of two different users in some time iterval
    //ie socket is open but not closed
    /* openConn =[
    {
      socketId : "ojIckSD2jqNzOqIrAGzL",
      products:[1234,1235,1236,1237,1238,1239]
    },
    {
      socketId : "pjsckSD2jqNzOqIrAG6L",
      products:[1234,1235,1236,1237,1238,1230]
    }
    ];*/

    setInterval(() => {
      let pageIds = [];
      openConn.forEach(item => {
         pageIds.push(item);
       });
       let topBids = queryItems(pageIds);//I am not adding this , sonce it is out of scopre , It will return data for pdt pageIds
       // It will be a total of 7 different products as second users product have only 1 id of pdt as different

       socket.on("sendAllBids",async function(data, callback){
          callback(topBids);
       })

    }, 10000); // THis is the time interval sample


    socket.on("disconnect",async () =>{
      openConn = openConn.filter((user) => user.socketId != socket.id);
    });

  });

客户端代码如下所示

var sock = io.connect("https://mysocketserver.com/", {upgrade: false});

  sock.emit("userInit", {
    data: listArr // list of pdtIds
  }, function(data) {

  });

  sock.emit("sendAllBids", {}, function(data) {
    console.log(data);// All bids from server
  });

有人能帮我提供一个优化的解决方案吗?因为setInterval适用于每n个客户端,我只需要执行一次服务器端代码,并将结果广播给所有n个连接的客户端
先谢了

zwghvu4y

zwghvu4y1#

您的问题和代码令人困惑,缺少一些部分。
如果你想从数据库发送数据到所有客户端每5秒然后这样做

const io = new Server(/* ... */)

io.on('connection', (/* ... */) => {
  //...
})

// main part
setInterval(async () => {
  try {

    const topBids = await topBids()
    io.of('/').emit('topBids', topBids)

  } catch (err) {
    console.error(err)
  }
}, 5 * 60 * 1000)

相关问题