刷新时套接字 io 多个连接

时间:2020-12-30 07:17:13

标签: socket.io

我正在使用多个命名空间和房间制作 socket io 网站,并从 mongodb 检索数据。但是当我在连接后刷新时,它会连接多次,如果我发送消息请求,它会被多次推送到数据库中。它在一个命名空间中运行良好。问题是多次生成的 io.of('ns').on('connection') 。如果我将其更改为 io.once,则切换命名空间后它不会再次连接。

Server Code 

    io.of(namespace.endpoint).on('connection',(nsSocket)=>{
   
     //  var roomss= Roomlist['Sample'];
  
      nsSocket.emit('nsroomload',roomss);

      nsSocket.on('joinroom',(roomName,Member)=>{
        
        const roomArray = Array.from(nsSocket.rooms);
        const roomLeave= roomArray[1];
        
   
        nsSocket.leave(roomLeave);
        updateUsers(namespace,roomLeave);
        nsSocket.join(roomName);

        const nsRoom = roomss.find((room)=>{ return room.roomTitle===roomName});
       
        let chat= chatList[nsRoom.roomId];
        let chatData = Chats[nsRoom.roomTitle];
        nsSocket.emit('historycatchup',{data:chatData,chat:chat});
        updateUsers(namespace,roomName);
      })
      
     nsSocket.on('newmessagetoserver',(data)=>{
       const msg = data.msg;
      const fullmsg ={
       msg:msg, time:Date.now(), username:username
      };
      const roomArray = Array.from(nsSocket.rooms);
      const roomTitle=roomArray[1];
      const nsRoom = roomss.find((room)=>{ return room.roomTitle===roomTitle});
      chatList[nsRoom.roomId].push(fullmsg);
      console.log(chatList[nsRoom.roomId]);
      Rooom.find({'roomTitle':roomTitle}).then(room=>{
        Chat.create({
         msg:msg, time:Date.now(), username:username
        },function(err,chat){
         room[0].data.push(chat);
         room[0].save();
        })
        
      })
      io.of(namespace.endpoint).to(roomTitle).emit('messagetoclient',fullmsg);
  //   nsSocket.broadcast.emit('messagetoclient',msg);
     }) 

   
    nsSocket.on('disconnect',function(){
     nsSocket.disconnect();
//]\\\       console.log('disconnect');
    })
    })
    
  })

0 个答案:

没有答案