I'm trying to create a simple game using Node.js among other things. But I'm having some issues.
The first player connects, and everything is fine. When the second player connects however, In the first window, both players appear. In the second window only player 2 is shown. Also, if I move player 2, in the second window, it doesn't move in the first window
here is the server side:
fs.createWriteStream("/Users/thomas/Desktop/connectedPlayers.md");
var players;
game.sockets.on('connection', function(socket){
fs.appendFile("/Users/thomas/Desktop/connectedPlayers.md", socket.id + '\n', function(err) {
if(err) {
console.log(err);
} else {
console.log("The file was saved!");
}
});
fs.readFile("/Users/thomas/Desktop/connectedPlayers.md", function(err, file){
if(err){
console.log(err);
}else{
players = file.toString().split('\n');
//When a player connects, all the players will get this message.
game.sockets.emit('entrance', {
id: socket.id,
players: players,
coordinates: {x: socket.x, y: socket.y},
message: 'Player ' + socket.id + ' is online'
});
}
});
});
I'm storing all the connected players to a text-file, store that in an array, which I can access on the client side:
socket.on('entrance', function(data){
for(var i = 0; i < data.players.length; i++){
new Player(data.players[i]).init();
}
//console.log(data.message);
isCalled = true;
});
I'd really appreciate some help/insight. Thanks!
you need to use broadcast for all or you loop over all connections: