socket.emit不向发件人发送消息

时间:2017-04-20 18:04:05

标签: node.js express socket.io

  1. 'socket.emit '没有向发送邮件的客户端发送邮件,而
  2. 'socket.broadcast.emit'向所有客户端(包括发件人)发送邮件。
  3. 我无法弄清楚我在这里缺少什么。 对于第二种情况,我在发送消息时检查了socket.id并在收到响应时记录了它,结果是相同的

    socket.js

    var socket = require('socket.io')(),
    socketApi = {};
    
    socketApi.io = socket;
    
    socketApi.io.on('connection',(client) => {
        client.on('clientMessage', (msg) => {
            console.log('hi');
            client.emit('serverMessage',msg);
        })
        client.on('disconnect',() => {
            socketApi.io.emit('serverMessage','client is disconnected');
            console.log('disconnected');
        })
    })
    
    
    module.exports = socketApi;
    

    client.js

    getServerResponse() {
            socket.on('serverMessage',(msg) => {
                    console.log(msg);
                })
        }
    

1 个答案:

答案 0 :(得分:0)

根据文档broadcast.emit发送给除发件人之外的所有人,而emit仅发送给发件人:https://socket.io/docs/emit-cheatsheet/

我遇到了同样的问题,所以我最终都打电话给他们:

// socket.io server
io.on('connection', socket => {
  socket.on('message', (data) => {
    messages.push(data)
    socket.broadcast.emit('message', data) // sends to all except the sender
    socket.emit('message', data)  // sends to the sender
  })
})