如何在SocketIO中获取Socket对象的'id'属性?

时间:2019-09-01 19:21:06

标签: javascript reactjs socket.io

基本上,我想做的是获取Socket对象的'id'属性,以将当前的每个客户端套接字ID保存到数据库中,但是却在努力获取'id'属性。我在console.log中看到了它,但是我无法获取该值本身。

componentDidMount() {
this.addUpdateCurrentRequestsView();
const firstSocket = primarySocket('http://localhost:3001');
console.log(firstSocket.id)// this is undefined
console.log(firstSocket) //id property is visible in console
this.registerUpdateCurrentSocket(firstSocket.id);

}

2 个答案:

答案 0 :(得分:0)

您需要处理连接中的事情。

io.on('connection', socket => {
 //socket is here
})

您检查过文件吗?

答案 1 :(得分:-1)

我相信我是通过反复试验解决此问题的。如果你们遇到过即使属性显示在console.log中也无法访问的问题,我相信这是一个异步的问题,可以这么说。所以我尝试了这段代码。

let firstSocketIDAssignmentChecker = setInterval(()=>{
    if (firstSocket.id!==undefined){
        this.registerUpdateCurrentSocket(firstSocket.id);
        clearInterval(firstSocketIDAssignmentChecker);
    }
},100);

这可行。