【问题标题】:Unable to get the socket id on the front end前端无法获取socket id
【发布时间】:2021-07-16 17:50:07
【问题描述】:

我需要在前端获取每个套接字的 ID,以便稍后我可以区分每个连接。当我打印 socketRef.current 时,我可以清楚地看到其中的任何内容,甚至可以看到其中的“id”,但只有“id”是我无法从那里打印的东西(如果我打印“io”或“ids”它可以工作)。为什么我不能打印“id”字段?有没有办法从后端正确获取 id?

const socketRef = useRef();

useEffect(() => {
    socketRef.current = io.connect('http://localhost:5000')
    console.log(socketRef.current.id)

}, []);

【问题讨论】:

    标签: reactjs express user-interface websocket socket.io


    【解决方案1】:

    连接 io 并在套接字上 connect 获取 socket.id

    const socket = io.connect('http://localhost:5000');
    socket.on("connect", () => {
      console.log(socket.id);
    });
    

    【讨论】:

      【解决方案2】:

      我相信需要先等待connect

      useEffect(() => {
        socketRef.current = io.connect('http://localhost:5000')
        socketRef.current.on('connect', ()=> {
        console.log(socketRef.current.socket.sessionid);
      });
          }, []);
      

      【讨论】:

        猜你喜欢
        • 2012-09-30
        • 2022-01-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多