组件安装时如何获取 socket.on("test", count)) 当前值?

Posted

技术标签:

【中文标题】组件安装时如何获取 socket.on("test", count)) 当前值?【英文标题】:how to get socket.on("test", count)) current value when component mounted?组件安装时如何获取 socket.on("test", count)) 当前值? 【发布时间】:2022-01-20 16:29:42 【问题描述】:
import ...
let socket;

const Game = () => 
const ...

  const [userCount, setUserCount] = useState(0);
  

  const scrollToBottom = () => 
    endToMessages.current?.scrollIntoView( behavior: "smooth" );
  ;

  const  _id, username  = JSON.parse(localStorage.getItem("user")).user;

  useEffect(() => 
    socket = io(process.env.REACT_APP_BASE_URL);
    socket.emit("game_lobby",  id: _id, username, room: gameInfo.name );

    return () => socket.disconnect();
  , [_id, username, gameInfo.name]);

  useEffect(() => 
    socket.on("message", ( user, text ) => 
      setMessages((prev) => [...prev,  user, text ]);
      scrollToBottom();
    );

    socket.on("user_count",(count) => 
      setUserCount(count);
    )

  , []);

  console.log("Current user count",userCount);

  const sendMessage = () => 
    ...
  ;


  return (
    <div className="game section">
       ...
    </div>
  );
;

export default Game;

服务器端:

import  Server  from "socket.io";

const socketApi = (server) => 
  const io = new Server(server, 
    cors: 
      origin: ["https://mook-f2b4e.web.app", "http://localhost:3000"],
      methods: ["GET", "POST"],
    ,
  );

  io.on("connection", (socket) => 
    socket.on("disconnect", () => 
      console.log(`user $socket.id had left`);
    );

    socket.on("game_lobby", async ( id, username, room ) => 
      console.log("We have a new connetion.");
      socket.join(room);

      const roomClients = await (await io.in(room).fetchSockets()).length;
      console.log(roomClients);
      io.to(room).emit("user_count",  count: roomClients );

      socket.on("disconnect", () => 
        io.to(room).emit("user_count",  count: roomClients );

      );

      
      socket.emit("message", 
        user: "Admin",
        text: `$username welcome to $room room`,
      );
    );

    socket.on("send_message", ( name, message, room ) => 
      io.to(room).emit("message",  user: name, text: message );
    );
  );

  return io;
;

export default socketApi;

大家好。当我尝试在组件挂载时获取用户数但我不能。当组件第一次挂载时,我得到 0 值。如果其他人加入房间,那么我可以获得它的当前值。如果我能正确解释的话,我的意思是说房间里有 3 个人,我后来加入了那个房间。现在房间里有 4 个人,但我从 console.log("Current user count", userCount) 获得 0 值,如果第 5 个人加入房间,那么我可以从服务器获得当前值。

【问题讨论】:

【参考方案1】:

我相信您需要服务器有一个变量来跟踪活跃用户。所以connectiononlineUsers 增加一个变量,然后在disconnect 上从onlineUsers 中减去一个

在此处查看参考 => https://***.com/a/10276446/3124019

【讨论】:

以上是关于组件安装时如何获取 socket.on("test", count)) 当前值?的主要内容,如果未能解决你的问题,请参考以下文章

与 Socket.io 反应 - 在“socket.on”事件上不断地重新渲染

如何在前端获取 socket.on 函数?事件被触发和处理。我正在使用 socket.io、NodeJS 服务器和 Redis.io

一个特定的“socket.on()”在客户端不起作用

Node net.Socket.on("data") 事件是不是有保证的顺序?

socket.io useEffect 清理函数 react

如何在反应中使用socket.on?