Node.js WebSocket广播

vhy*_*yea 3 javascript websocket node.js

我在Node.js中使用ws库用于WebSockets,我正在从库示例中尝试这个示例:

var sys = require("sys"),
    ws = require("./ws");

  ws.createServer(function (websocket) {
    websocket.addListener("connect", function (resource) { 
      // emitted after handshake
      sys.debug("connect: " + resource);

      // server closes connection after 10s, will also get "close" event
      setTimeout(websocket.end, 10 * 1000); 
    }).addListener("data", function (data) { 
      // handle incoming data
      sys.debug(data);

      // send data to client
      websocket.write("Thanks!");
    }).addListener("close", function () { 
      // emitted when server or client closes connection
      sys.debug("close");
    });
  }).listen(8080);
Run Code Online (Sandbox Code Playgroud)

一切都好.它可以工作,但是运行3个客户端,然后发送"Hello!" 从一个将使服务器只回复"谢谢!" 发送消息的客户端,而不是全部.

我怎么播"谢谢!" 当有人发送"你好!"时,所有连接的客户端?

谢谢!

ont*_*ia_ 8

如果您想发送给所有客户,您必须跟踪它们.这是一个示例:

var sys = require("sys"),
    ws = require("./ws");

// # Keep track of all our clients
var clients = [];

  ws.createServer(function (websocket) {
    websocket.addListener("connect", function (resource) { 
      // emitted after handshake
      sys.debug("connect: " + resource);

      // # Add to our list of clients
      clients.push(websocket);

      // server closes connection after 10s, will also get "close" event
      // setTimeout(websocket.end, 10 * 1000); 
    }).addListener("data", function (data) { 
      // handle incoming data
      sys.debug(data);

      // send data to client
      // # Write out to all our clients
      for(var i = 0; i < clients.length; i++) {
    clients[i].write("Thanks!");
      }
    }).addListener("close", function () { 
      // emitted when server or client closes connection
      sys.debug("close");
      for(var i = 0; i < clients.length; i++) {
        // # Remove from our connections list so we don't send
        // # to a dead socket
    if(clients[i] == websocket) {
      clients.splice(i);
      break;
    }
      }
    });
  }).listen(8080);
Run Code Online (Sandbox Code Playgroud)

我能够将它广播给所有客户,但并未对所有情况进行严格测试.一般的概念应该让你开始.

编辑:顺便说一下,我不确定10秒钟关闭是什么,所以我已经评论过了.如果您尝试向所有客户广播,那么它将毫无用处,因为它们会不断断开连接.