从一个打开的连接发出多个消息socket.io

时间:2016-06-24 15:52:40

标签: node.js socket.io

我是socket.io的新手,并试图弄清楚如何发送多条消息。这是我正在处理的场景,

function setupServer(server) {
    var socketIO = require("socket.io").listen(server);
    socketIO.sockets.on('connection', function (socket) {
        console.log("client is connected");
        socket.emit('update', { progress: "starting..." })
    });
}

我必须从另一种方法调用setupServer(服务器),我正在接收"开始......"在客户端。

但问题是,我希望稍后发送更多/多条消息。无法发送消息数组,因为我的应用程序正在构建消息字符串,例如每10毫秒(在回调函数中),并且我想在创建它们后立即发送。

任何解决方案?是否可以让套接字对象引用在此函数之外重用?

1 个答案:

答案 0 :(得分:0)

来自socket.io docs:http://socket.io/docs/#broadcasting-messages

  

要进行广播,只需添加广播标志即可发出和发送方法调用。广播意味着向除了启动它的套接字以外的所有人发送消息。

function setupServer(server) {
    var socketIO = require("socket.io").listen(server);
    socketIO.on('connection', function (socket) {
        console.log("client is connected");
        socket.emit('update', { progress: "starting..." });

        startBroadCastFromSocket(socket, 3); 

        socket.on('disconnect', function(){
          stopBroadcastFromSocket(socket);
        });
    });

    // broadcast message to all sockets
    setInteval(function() {
      broadcastMessageToEveryone(socketIO, {body: 'Hello everyone (FROM SERVER)', timestamp: new Date());
    }, 1000);
}

function broadcastMessageToEveryone(io, body) {
  io.emit('message', {body: body, timestamp: new Date()});
}

function broadcastMessageFromSocket(socket, body) {
  socket.broadcast.emit('message', {body: body, timestamp: new Date()});
}

var socketIntervals = {};

function stopBroadcastFromSocket(socket) {
  if(socketIntervals[socket.id]) {
    clearInterval(socketIntervals[socket.id]);
  }
}

function startBroadcastFromSocket(socket, seconds) {
  socketIntervals[socket.id] = setInterval(function(){
    broadcastMessageFromSocket(socket, 'Hello!');
  }, seconds*1000);
}