在socket.io中发出不起作用

时间:2022-08-22 15:26:46

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

我创建了一个相当简单的socket.io项目来证明'sockets.emit'似乎有些问题。

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

我在这里创建了一个git:https://github.com/dirkk0/minimalsocket

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

有问题的行是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:

因此,作为一个workaroud,我遍历客户端发送消息,这可以正常工作:

    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.

我在Ubuntu 12.04上测试了节点v0.10.24,npm 1.3.21,socket.io 0.9.16,express 3.4.7和MacOSX节点0.10.12。还有MacOSX上的Safari,Firefox,Chrome和Windows7上的Chrome。结果是一致的。

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.

编辑:是的,我忽略了我必须给通道一个名字(由于某种原因不需要.send),如:io.sockets.emit('message',JSON.stringify(msg))socket .emit没有被打破。

1 个解决方案

#1


3  

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

您忘记了emit()的事件名称,它应该是io.sockets.emit('message',yourObject)或将其更改为io.sockets.send(yourObject);

Syntaxs of emit() and send():

emit()和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) (???) 

#1


3  

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

您忘记了emit()的事件名称,它应该是io.sockets.emit('message',yourObject)或将其更改为io.sockets.send(yourObject);

Syntaxs of emit() and send():

emit()和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) (???)