Node.js WebSocket Broadcast

I am using the ws library for WebSockets in Node.js and I am trying this example from the sample libraries:

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

All OK. It works, but, for example, starts 3 clients and sends "Hello!". from one will make the server respond only "Thank you!" to the client who sent the message, not to everyone.

How can I broadcast "Thank you!" for all connected clients when someone sends “Hello!”?

Thank!

+3
source share
2 answers

If you want to send to all customers, you must track them. Here is an example:

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

, . .

EDIT: , , 10 , . , , .

+8

socket.io. - , (WebSockets Safari, Chrome, Opera Firefox, Firefox Opera - ws-).

+3

All Articles