首页 > 解决方案 > socket.io 获取数据 io.sockets.clients(); 不再工作

问题描述

在您可以在前端创建具有用户属性的对象并将其分配给每个连接的 socket.user 属性之前,请在后端使用下面这样的代码。

socket.on("new_visitor", user => {
    console.log("new_visitor", user);
    socket.user = user;
    emitVisitors();
});

然后通过套接字对象检索所有这些数据,例如。

 const getVisitors = () => {
     let clients = io.sockets.clients().connected;
     let sockets = Object.values(clients);
     let users = sockets.map(s => s.user);
     return users;
 };

//frontend
  componentWillMount() {
    axios.get('http://geoplugin.net/json.gp').then(res => {
      const {
        geoplugin_request,
        geoplugin_countryCode,
        geoplugin_city,
        geoplugin_region,
        geoplugin_countryName
      } = res.data;
      const visitor = {
        ip: geoplugin_request,
        countrycode: geoplugin_countryCode,
        city: geoplugin_city,
        state: geoplugin_region,
        country: geoplugin_countryName
      } 

      socket.emit("new_visitor", visitor);

      socket.on("visitors", visitors => {
        this.setState({
          visitors: visitors
        })          
      })
    });
  }

但是现在 io.sockets.clients 不再工作并且不被识别为函数。提供的每个 API 似乎都只返回 Id。对于任何知道解决方法的人,请告诉我们。非常感谢。

标签: javascriptnode.jssocket.io

解决方案


问题:如何为每个套接字保存自定义数据(服务器端)

对于连接到socket-io服务器的每个套接字,您希望能够存储一些参考所述套接字的自定义数据,以便稍后其他套接字可以检索此信息。

解决方案:添加一个简单的内存存储(服务器端)

我强烈建议不要添加任何东西或改变socket对象。而是使用套接字id为所有连接的套接字维护一个简单的内存存储。

请注意:以下片段只是指针,并不意味着只是复制粘贴。相反,请尝试使用它们来了解您的问题并根据您的需要进行调整。

服务器端

const store = {};

io.on('connection', function (socket) {

  // add socket to store, like this
  // note 'data' is null at this point, yet needs to be set
  store[socket.id] = {
    socket : socket, 
    data   : null
  }

  socket.on('SET_CLIENT_DATA', function (clientdata) {
    // here we receive data from frontend, and add it to the serverside reference
    store[socket.id].data = clientdata;
    
    // once a socket updates his custom client data
    // emit all custom data to all clients
    io.emit('ALL_CONNECTED_CLIENTS', Object.values(store).map(e => e.data));
  });

  socket.on('disconnect', function () {
    // if socket disconnects, make sure to remove the reference in your store
    delete store[socket.id];
  });

});

客户端

socket.emit("SET_CLIENT_DATA", clientdata);

socket.on("ALL_CONNECTED_CLIENTS", (allclients) => {
  
/* here the client receives all custom client data that we kept serverside for each connected client */ 
/* do some more code here */

});

推荐阅读