3

I'm using the ws library for WebSockets in Node.js and I'm trying this example from the library examples:

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 running 3 clients, for instance, and sending "Hello!" from one will make the server only reply "Thanks!" to the client which sent the message, not to all.

How can I broadcast "Thanks!" to all connected clients when someone sends "Hello!"?

Thanks!

2 Answers 2

8

If you want to send out to all clients, you have to keep track of them. Here is a sample:

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

I was able to get it to broadcast to all clients, but it's not heavily tested for all cases. The general concept should get you started though.

EDIT: By the way I'm not sure what the 10 second close is for so I've commented it out. It's rather useless if you're trying to broadcast to all clients since they'll just keep getting disconnected.

1
  • onteria_, very thanks! work! I'm get started! :-) Thanks(And all other's thanks for answer's), Good Luck!
    – vhyea
    May 23, 2011 at 15:04
2

I would recommend you to use socket.io. It has example web-chat functionality out of the box and also provides abstraction layer from the socket technology on client (WebSockets are supported by Safari, Chrome, Opera and Firefox, but disabled in Firefox and Opera now due to security vulnerabilities in ws-protocol).

4
  • 1
    Thanks for recommend, answer, but I'm think after 1 year's(+/-) all Browser's support's WebSocket's. :-)
    – vhyea
    May 23, 2011 at 14:22
  • Websockets are supported in Chrome, and Firefox r (though disabled by default in FF)
    – Matt
    May 23, 2011 at 14:33
  • @Matt Edited the text of answer.
    – bjornd
    May 23, 2011 at 14:38
  • @vhyea: just to clarify @bjornd's answer. Socket.IO is a client and server library that abstracts communication. If WebSockets is available, then Socket.IO will use that. If Flash is available then Socket.IO can use web-socket-js which is a Flash based fallback/shim/polyfill for WebSockets. If neither is available then Socket.IO uses slower long-poll methods. In other words, Socket.IO abstracts the underlying transports.
    – kanaka
    May 31, 2011 at 19:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.