I am building a game using socketio.
The server stores the number of players, when it goes to 2, game start.
However, when I open two browser one by one, only the first one(not the latter one) receive the game start message.
Client side:
var socket = io.connect('http://localhost:8080');
socket.on('connected', function (data) {
$('#status').html('You are connected');
socket.emit('1 party connected');
});
socket.on('game start', function (data) {
$('#status').html('game start');
});
Server side:
var app = require('http').createServer(handler)
, io = require('socket.io').listen(app)
, fs = require('fs')
app.listen(8080);
var connected_parties_no = 0;
io.sockets.on('connection', function (socket) {
socket.emit('connected', { hello: 'world' });
socket.on('1 party connected', function () {
connected_parties_no++;
console.log(connected_parties_no.toString()+' parties are connecting.');
if (connected_parties_no == 2) {
game_start(socket);
}
});
socket.on('disconnect', function () {
connected_parties_no--;
});
});
function game_start(socket) {
socket.broadcast.emit('game start');
}
socket.broadcast.emit('game start');
will send the 'game start' event to everyone except `socket. You're most likely looking for
io.sockets.emit('game start');