javascript - 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。对于任何知道解决方法的人,请告诉我们。非常感谢。
解决方案
问题:如何为每个套接字保存自定义数据(服务器端)
对于连接到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 */
});
推荐阅读
- java - URL 参数正在被修改
- matlab - 如何将此特定时间戳编号转换为日期?
- r - rtweet 函数“get_followers”不返回任何内容
- android - 在 Android 上,如何在网络层 (IP) 上捕获传入的数据包?
- python - 阻止文本小部件随字体大小改变大小?
- claudiajs - 如何在使用 Claudia 部署的 express js 应用程序中设置 Lambda 上下文
- tws - IB Api 通过传递交换名称获取符号列表
- node.js - 将未在请求正文中传递的字段存储到 mongodb 为 null 或空(集合使用 mongoose 模式定义)
- node.js - Angular httpclient CORS 请求返回 404 错误
- javascript - 在按钮单击时将 Angular 组件 (HTML) 动态插入到 TineMCE 编辑器