1

I created a fairly trivial socket.io project to prove that something seems to be wrong with 'sockets.emit'.

I created a git here: https://github.com/dirkk0/minimalsocket

The lines in question are https://github.com/dirkk0/minimalsocket/blob/master/server.js#l17-21

    // this should work but doesn't
    io.sockets.emit(JSON.stringify(msg))

which doesn't work.

So as a workaroud I iterate through the clients to send a message, which works fine:

    io.sockets.clients().forEach(function (socket) {
        socket.send(JSON.stringify(msg));
    });

I tested on Ubuntu 12.04 with node v0.10.24, npm 1.3.21, socket.io 0.9.16, express 3.4.7 and on MacOSX with node 0.10.12. Also Safari, Firefox, Chrome on MacOSX and Chrome on Windows7. The results are consistent.

Am I overlooking something obvious?

Thanks, Dirk

EDIT: yes, I overlooked that I had to give the channel an name (which for some reason isn't needed with .send), like in: io.sockets.emit('message', JSON.stringify(msg)) socket.emit is not broken.

dirkk0
  • 2,460
  • 28
  • 34
  • Good repository and readme :) – damphat Jan 01 '14 at 13:22
  • What do you mean by `doesn't work`? As in no message is sent, or an empty message is sent? Also, you may find this question relevant: http://stackoverflow.com/questions/11498508/socket-emit-vs-socket-send – verybadalloc Jan 01 '14 at 14:01
  • 2
    Have you tried with io.sockets.emit('message', JSON.stringify(msg)) – damphat Jan 01 '14 at 14:04
  • 1
    @damphat is right: the first argument to `emit` should be a message name. You're using a JSON string as a name, which isn't in itself wrong (it'll be emitted), but I doubt that you're listening on that exact string on the client side. – robertklep Jan 01 '14 at 14:10
  • Yes, was it. After I changed it to 'io.sockets.emit('message', JSON.stringify(msg))' it worked. @damphat if you want to collect points on this, add the answer, and I'll gladly accept it. Thanks (also for your first comment :-) and to the others)! – dirkk0 Jan 01 '14 at 14:24

1 Answers1

3

You forgot an event name for emit(), that should be io.sockets.emit('message', yourObject) or change it to io.sockets.send(yourObject);

Syntaxs of emit() and send():

// @param yourEventName is a string
// @param yourObject is an serializable object (that mean you can stringify it)
socket.emit(yourEventName, yourObject);

// @param yourObject is a serializable object
socket.send(yourObject) // equipvalent to socket.emit('message', yourObject) (???) 
damphat
  • 18,246
  • 8
  • 45
  • 59