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