我想创建具有统一性和nodejs的在线tic tac,当我进入房间中的两个玩家时,两个玩家自动进入房间! 注意:每个房间最多有两个玩家
问题:
玩家在连接后立即断开连接
和
io.sockets.clients()。长度不起作用
var io = require('socket.io')(process.env.PORT || 3000);
var shortid = require('shortid');
console.log('server started');
var usernames = {};
var ids = {};
var rooms = [];
var roomExist = false;//true if a room exist with one player in there
var lastRoom ; // id of room with one player
var numClients = 0;
io.sockets.on('connection',function(socket){
socket.on('addUser',function(username){
socket.username = username;
});
socket.id = shortid.generate();
socket.emit('yourId',socket.id);
if (roomExist){//Player 2 joined
socket.room = lastRoom;
socket.join(lastRoom);
roomExist = false;
console.log('J client by id' ,socket.id,'by name',socket.username,'joined room',socket.room);
console.log('number of clients is :',io.sockets.clients().length);
socket.broadcast.to(socket.room).emit('spawn');
socket.on('move',function(data){
console.log('client moved',JSON.stringify(data));
socket.broadcast.to(socket.room).emit('move',data);
});
}
else {//Player 1 joined
lastRoom = shortid.generate();
rooms.push(lastRoom);
socket.room = lastRoom;
socket.join(lastRoom);
roomExist = true;
console.log('C client by id' ,socket.id,'by name',socket.username,'joined room',socket.room);
console.log('number of clients is :',io.sockets.clients().length);
socket.emit('wait'); // wait for player 2
socket.on('move',function(data){
console.log('client moved',JSON.stringify(data));
socket.broadcast.to(socket.room).emit('move',data);
});
}
socket.on('disconnect',function(){
delete usernames[socket.username];
delete usernames[socket.username];
console.log('client',socket.username,'disconnected');
io.sockets.emit('updateusers', usernames);
socket.broadcast.emit('updatechat', 'SERVER', socket.username + ' has disconnected');
socket.leave(socket.room);
});
});
答案 0 :(得分:0)
回答可能有点晚,但是在socket.io 2.2.0中,您应该使用:
io.sockets.clients.length
您在客户之后有括号