【问题标题】:nodejs socket.io clients not exchange emitted messagesnodejs socket.io 客户端不交换发出的消息
【发布时间】:2019-01-02 02:11:15
【问题描述】:

我对 nodejs 和 socket.io 有一个奇怪的行为 在节点服务器 socket.io 上运行良好:

...
const nodeServer = app.listen(app.get('port'), () => {
    console.log(
        '%s App is running at http://localhost:%d in %s mode',
        chalk.green('✓'),
        app.get('port'),
        app.get('env')
    );

});
var io = require('socket.io').listen(nodeServer);
io.on('connection', function(socket){
    socket.on('new_message', function(msg){
        console.log('emit message: ' + msg.message);
        socket.emit('new_message', msg);
    });
});

在客户端,我有一个简单的调用来发送和接收数据:

<script src="socket.js"></script>
<script src="https://code.jquery.com/jquery-1.11.1.js"></script>
<script>
    const chat = io.connect('http://xxx.xxx.xxx.xxx:4000');

  // ..... Send message
  document.getElementById('sendChat').addEventListener('click', function(event){
     chat.emit('new_message', {message: document.getElementById('message').value});
  })

  // ..... Receive message
  chat.on('new_message', (data) => {
     console.log(data.message)
     $('.chatRoom').append('<p class="message">'+data.message+'</p>');
  })
</script>

现在我将打开 2 个客户端:

使用这个脚本,当收到带有“new_message”事件的消息时,我应该打印一个控制台并将消息附加到一个 div。 当我从第一个客户端发送消息时,第二个客户端没有收到消息,反之亦然,但是消息显示在当前客户端的 .chatRoom div 上,所以我认为服务器已收到并很好地发出消息.

node js 服务器同时输出来自client1 和client2 的消息

有人对此有解释吗?

谢谢。

【问题讨论】:

  • 在服务器上,将socket.emit替换为io.emit

标签: node.js socket.io


【解决方案1】:

socket.emit 就是这样工作的,它向发送者(当前客户端)发回一条消息。

要发送给所有客户端,请使用(服务器端):

io.emit('message', "this is a test");

使用您的代码:

var io = require('socket.io').listen(nodeServer);
io.on('connection', function(socket){
    socket.on('new_message', function(msg){
        console.log('emit message: ' + msg.message);
        io.emit('new_message', msg);
    });
});

查看Socket.IO cheatsheetrooms and namespaces 的文档也可能有用。

希望对你有帮助!

【讨论】:

    猜你喜欢
    • 2014-01-20
    • 1970-01-01
    • 1970-01-01
    • 2013-06-29
    • 1970-01-01
    • 2019-03-15
    • 2013-02-21
    • 2021-04-08
    相关资源
    最近更新 更多