如何有效地处理使用套接字的招标网站.减少服务器负载的IO和nodejs



在我的一个网站中,我需要在其中一个页面上显示前6个竞标产品,其中最高出价值应该在不加载页面的情况下更新。我需要使用nodejs套接字来实现这一点。Io,希望将数据广播给登陆该页面的多个活跃用户,可能需要5分钟的时间间隔。我更喜欢套接字,因为我可以通过每5分钟广播多个用户的数据来减少数据库负载,但我有一些困惑,比如它是否工作正常

我已经在下面添加了服务器端和客户端代码示例,

Nodejs插座。IO服务器端代码。

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
});

有人可以帮助我给每n个客户端的setInterval工作一个优化的解决方案,我需要执行服务器端代码只有一次和广播结果到所有n个连接的客户端

Thanks in advance

你的问题和代码很混乱,缺少几个部分。

如果你想每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)

let topBids = [];
io.on('connection', async function(socket) {
socket.on("userInit",data=>{
objIndex = openConn.findIndex((obj => obj.socketId == socket.id));
if(typeof openConn[objIndex] !== "undefined")
openConn[objIndex].data = data.data;
});
socket.on("disconnect",async () =>{
openConn = openConn.filter((user) => user.socketId != socket.id);
});
});
setInterval(() => {
topBids = queryItems(pageIds);
io.emit('sendAllBids', { data: topBids });
}, 10000);

相关内容

  • 没有找到相关文章

最新更新