【问题标题】:socket.emit not emitting messages to the sendersocket.emit 不向发送者发送消息
【发布时间】:2017-09-17 12:21:19
【问题描述】:
  1. 'socket.emit' 不向发送它的客户端发送消息,而
  2. 'socket.broadcast.emit' 向包括发送者在内的所有客户端发送消息。

我无法弄清楚我在这里缺少什么。 对于第二种情况,我在发送消息时检查了 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);
            })
    }

【问题讨论】:

  • in client.js - 你调用了`getServerResponse'函数吗?
  • 是的...当我使用 SocketAPI.io.emit 或 client.broadcast.emit 时收到响应
  • client.on('clientMessage', (msg) => {;这里的分号是干什么的?
  • 更新了代码..只是发布问题时的拼写错误,问题仍然存在
  • 你会用console.log(client);代替console.log('hi');吗?

标签: node.js express socket.io


【解决方案1】:

根据文档,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
  })
})

【讨论】:

    猜你喜欢
    • 2015-07-28
    • 2016-04-14
    • 2015-03-19
    • 1970-01-01
    • 1970-01-01
    • 2020-12-09
    • 1970-01-01
    • 2019-05-20
    • 1970-01-01
    相关资源
    最近更新 更多