【问题标题】:Too many connections Socket.ioSocket.io 连接太多
【发布时间】:2020-08-05 11:33:23
【问题描述】:

我已经在 React、Node 和 Socket.io 上制作了聊天应用程序,每当我刷新我的页面或改变我的房间时,我都有额外的连接。如何关闭这个先前的连接以及如何管理它?我找到了 socket.leave() 和 socket.off() 但它对我不起作用:/ 提前致谢!

服务器端

let listOfRooms = [];
var allClients = [];

mongoose
   .connect(
      `mongodb+srv://${process.env.DB_USER}:${process.env.DB_PASSWORD}@cluster0-lnoai.mongodb.net/${process.env.DB_NAME}?retryWrites=true&w=majority`
   )
   .then(() => {
      io.on('connection',(socket)=>{
         allClients.push(socket.id)
         console.log(allClients);

         socket.on('initRoom',({userData,roomList})=>{
            listOfRooms = roomList;

            listOfRooms.forEach(room=>{
            const nsp = io.of(room.id);
            nsp.on('connection', (nsSocket)=>{
                  nsSocket.on('joinRoom', ( data ) => {
                     const {userData, roomId} = data;
                     console.log(`joined to ${room.title}`);

                  });

                  nsSocket.on('sendMessage', (newMsg ) => {
                     const {roomId} = newMsg;
                  });
                  nsSocket.on('disconnect', () => {
                     console.log('disconnected nsSocket');

                     nsSocket.disconnect();
                     // removeUser(nsSocket.id)
                     // nsSocket.leaveAll(nsSocket.id);
                  })
               });
         })
      })
   })
})
.catch(err => {
   console.log(err);
});

客户端

useEffect(() => {
    socket = io(host);
    const roomList = [];
    namespaces.forEach((ns) => {
      ns.rooms.forEach((room) => {
        roomList.push(room);
      });
    });
    socket.emit('initRoom', { userData, roomList });
  }, []);

  useEffect(() => {
    const roomId = props.location.pathname.slice(1, props.location.pathname.length);
    roomSocket = io(`${host}${roomId}`);
    console.log(roomSocket);
    const data = {userData, roomId}
    roomSocket.emit('joinRoom', data);

    return () =>{
      roomSocket.emit('disconnect');

      roomSocket.off()
      socket.off()
    }
  }, [endpoint, props.location.pathname]);

  useEffect(() => {
    roomSocket.on('message', (message) => {
      console.log('tu patrz');
      const updatedMessages = [...messages, message];
      setMessages(updatedMessages);
    });

    roomSocket.on('roomData', ({ users }) => {
      setUsers(users);
      console.log('users:');
      console.log(users);
    });
  }, [messages, users]);

  const sendMessage = (newMsg) => {
    if (newMsg) {
      const roomId = props.location.pathname.slice(1, props.location.pathname.length);
      newMsg.roomId = roomId;

      roomSocket.emit('sendMessage', newMsg);
      setMessages('');
    }
  };

【问题讨论】:

    标签: node.js reactjs socket.io


    【解决方案1】:

    每次触发断开连接事件时尝试roomSocket.disonnect(true)

    但是,如果您想为每个客户端强制执行一个 socket.io 连接,那么您将必须实现某种身份验证系统,例如 passport.js,然后使用 cookie 或令牌来唯一标识用户。

    由于一个套接字 ID 只能有一个连接,如果您将套接字 ID 设置为用户的令牌或会话 ID,那么您将有效地限制客户端每次连接一个连接。

    【讨论】:

      猜你喜欢
      • 2016-09-15
      • 1970-01-01
      • 2011-07-13
      • 2013-05-09
      • 2018-08-04
      • 2017-12-27
      • 2011-03-05
      • 2014-07-22
      • 1970-01-01
      相关资源
      最近更新 更多