我正在尝试将连接的客户端列表添加到socket.io服务器,我尝试过以下操作: 使用socket.io-client
<!doctype html>
<html>
<head>
<meta content="charset=UTF-8">
<style type= "text/css">
html{
height:100%;
margin: 0;
}
body {font-family: Georgia; height:99%; margin: 0.25% 0}
div {position: absolute}
#cntr {
width: 1250px;
display: block;
position: relative;
top: 0;
float: none;
margin: 0 auto;
background-color: white;
height:100%;
}
</style>
</head>
<body style="background-color: #708090">
<div id="cntr">
<div style="right: 0; top: 0; width:100%; height: 261px; border-bottom: solid 1px black">
<a href="index.html"><img src= "png/logojan2.png" style="position: absolute; top:55px; left: 240px"></a>
<img src="png/rze.png" style="position: absolute; right: 50px; bottom:24px">
</div>
<div style="top: 300px; left: 50px; height: 60%; width:300px">
<div style="position: fixed; background-color: black; height: inherit; width: inherit">
</div>
</div>
<div style="top:300px; left:400px; width:800px">
/*some long <p>'s of text here*/
</div>
</div>
</body>
</html>
这给出了:
io.socket.clients()
如何解决此问题?
答案 0 :(得分:1)
查找此代码:
var io = require('socket.io')(2558);
var shortId = require('shortid');
var clients = [];
io.on('connection',function(socket){
var currentUser;
socket.on('USER_CONNECT', function (){
console.log('Users Connected ');
for (var i = 0; i < clients.length; i++) {
socket.emit('USER_CONNECTED',{
name:clients[i].name,
id:clients[i].id,
position:clients[i].position
});
console.log('User name '+clients[i].name+' is connected..');
};
});
socket.on('PLAY', function (data){
currentUser = {
name:data.name,
id:shortId.generate(),
position:data.position
}
clients.push(currentUser);
socket.emit('PLAY',currentUser );
socket.broadcast.emit('USER_CONNECTED',currentUser);
});
socket.on('disconnect', function (){
socket.broadcast.emit('USER_DISCONNECTED',currentUser);
for (var i = 0; i < clients.length; i++) {
if (clients[i].name === currentUser.name && clients[i].id === currentUser.id) {
console.log("User "+clients[i].name+" id: "+clients[i].id+" has disconnected");
clients.splice(i,1);
};
};
});
socket.on('MOVE', function (data){
// currentUser.name = data.name;
// currentUser.id = data.id;
currentUser.position = data.position;
socket.broadcast.emit('MOVE', currentUser);
console.log(currentUser.name+" Move to "+currentUser.position);
});
});
console.log(“-------服务器正在运行-------”);
答案 1 :(得分:0)
在最新的socket.io中,io.socket.clients()
需要传递给它的回调,它将异步调用该回调:
io.socket.clients(function(err, connectedIds) {
if (!err) {
// connectedIds is an array of connected socket ids
}
});
我不知道为什么这个信息仅作为异步回调通过.clients()
提供,因为如果查看此函数的代码,则检索数据时不会涉及异步操作。也许有预期的异步操作或者它可能与用于聚类的redis适配器等事情有关。
同样的信息可以在对象形式中同步获得:
var clients = io.sockets.connected;
这将是一个对象,其中键是每个连接套接字的socket.id,值是套接字对象。
因此,您可以同步获取相同的连接套接字ID数组,如下所示:
var connectedIds = Object.keys(io.sockets.connected);
或者,您可以将其转换为连接的套接字对象数组,如下所示:
var connectedSocketArray = Object.keys(io.sockets.connected).map(function(id) {
return io.sockets.connected[id];
});