Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
685 views
in Technique[技术] by (71.8m points)

socket.io - Socket io multiple connections on refresh

I am making socket io website using multiple namespaces and rooms and retrieving data from mongodb. But when i refresh after connecting, it connects multiple times and if i send message request it is pushed multiple times into database. It is working fine in one namespace. The problem is io.of('ns').on('connection') which is generated multiple times. If i change it to io.once it is not connecting again after switching namespaces.

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...