I'm creating a voting feature using socket.io. Sockets are placed into rooms by a channelId. Whenever any socket in the room emits a vote event, i'm trying to emit the current vote-list to all sockets in that room.
My problem is that if I have Sockets A, B, C in the same room, votes from Socket A are visible to B and C (that is, B and C's on.('vote') listeners are called), but NOT to A itself.
What i expect to happen, is that if Sockets A, B, C are in the same room, and A emits a vote, All sockets A, B, C vote listeners will be called.
Client:
These listeners are defined within methods, but i've singled them out for clarity. All variables are defined.
const socket = io('https://localhost:3001')
socket.emit('join-channel',{
channelId: payload.channelId,
senderId: socket.id
})
socket.emit('vote',{
senderId: socket.id,
channelId: state.channelId,
vote: payload.vote,
userId: state.userId
})
socket.on(`vote`, function (data) {
store.commit(MUTATIONS.SET_VOTES, data)
});
Server
module.exports = (app,server) => { var io = require('socket.io')(server);
io.on('connection', function (socket) {
socket.on('join-channel',data=>{
socket.join(data.channelId)
})
socket.on('vote',data=>{
postVote(data)
let { channelId } = data
socket.to(channelId).emit(`vote`,STORE[channelId])
//socket.emit(`vote`,STORE[channelId]) //My workaround so that the socket's messages are emitted back to itself
})
});
};
My current workaround is to add socket.emit('vote',STORE[channelId]), so that it can emit data back to itself.
This is by design in the socket.io API. This form you were using:
socket.to(channelId).emit(...)
is specifically designed to send to all sockets in the channelId room EXCEPT socket.
If you want to send to ALL users in that room, then change the above code to:
io.to(channelId).emit(...)
Here's a quote from the socket.io doc for socket.to():
Sets a modifier for a subsequent event emission that the event will only be broadcasted to clients that have joined the given room (the socket itself being excluded).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With