我正在使用 node js 创建一个多人游戏网站。所以每次连接套接字时,我都会在这样的数组中添加该套接字
var users = [];
var games = [];
var joinKey = [];
var key = 0;
var usersKey = 101;
var gamesKey = 201;
io.sockets.on('connection', function (socket) {
socket.on('connect', function(){
console.log('connect');
var clientId = usersKey;
socket.clientId = clientId;
users[usersKey] = socket;
usersKey++;
socket.emit('getClientId', clientId);
console.log(socket.clientId + ' connected');
console.log('Total users: ' + users.length);
});
这里总用户显示 102,因为用户密钥是 101,它会自动记录从 0 到 100 的空白值。我猜这不正常。另外,如果我使用索引从其他数组中检索套接字,则如果索引是字符串,则它是未定义的,例如“g201”
socket.on('createNewGame', function(){
var game = [];
var clientId = socket.clientId;
game[clientId] = socket;
console.log(game);
var gameId = 'g' + gamesKey;
gamesKey++;
games[gameId] = game;
console.log('Total Games: ' + games.length)
socket.gameId = gameId;
var publicKey = ++key;
joinKey[publicKey] = gameId;
socket.emit('gameCreated', publicKey);
});
如果这是此处数组的行为,我不知道如何插入和获取