socketio广播消息只发送给一个

时间:2013-05-12 01:46:49

标签: node.js socket.io

我正在使用socketio制作游戏 服务器存储玩家数量,当游戏开始时为2,游戏开始 但是,当我逐个打开两个浏览器时,只有第一个(不是后一个)接收游戏开始消息 客户方:

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');
});

服务器端:

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');
}

1 个答案:

答案 0 :(得分:2)

socket.broadcast.emit('game start');

会将'game start'事件发送给`socket之外的所有人。你最有可能找

io.sockets.emit('game start');