probil / vue-socket.io-extended

:v::zap: Socket.io bindings for Vue.js and Vuex (inspired by Vue-Socket.io)
MIT License
629 stars 38 forks source link

Cannot receive socket.to(roomId).emit('xxx', data) from server #526

Closed loongmxbt closed 3 years ago

loongmxbt commented 3 years ago

I've stuck here for several time and hope someone can help. I've seen some related issues but still can't figure out how. https://github.com/probil/vue-socket.io-extended/issues/517 https://github.com/probil/vue-socket.io-extended/issues/455

Server

io.on('connection', function(socket) {
    socket.on('join', async({ userId, roomId }) => {
      try {
        socket.join(`${roomId}`)
        socket.to(`${roomId}`).emit('roomInfo', {
          action: 'join',
          roomname: roomname,
          username: username,
          roomusers: roomusers
        });
        socket.to(`${roomId}`).emit('message', {
          msg: `User ${username} Joined room ${roomname}`
        })
        socket.emit('test', {
          msg: 'test message'
        })

Client Vuex

socket_roomInfo ({ dispatch, commit }, data) {
      console.log('socket roomInfo')
      console.log(data)
    },
    socket_message({ dispatch, commit }, data) {
      console.log('socket message')
      console.log(data)
    },
    socket_test({ dispatch, commit }, data) {
      console.log('socket test')
      console.log(data)
    }

Only socket_test can receive data, socket_roomInfo and socket_message cannot receive data. When I modify server socket.to(${roomId}).emit('roomInfo') into socket.emit('roomInfo'), then I can receive data on client.

So my question is, how can I receive roomInfo event data on client vuex?

probil commented 3 years ago

Hey @loongmxbt 👋

Rooms are supported but there is a difference how you use it on the BE. The syntax you use in Vuex actions is correct.

But according to the docs, you need to trigger events on io (not on socket) in order to send message to all room participant:

Screenshot 2021-04-22 at 16 08 43

// sends message to all room member
io.to(roomId).emit('roomInfo', {
  action: 'join'
});

// sends message to all room members excluding the current client
// that's why you don't receive it (!)
socket.to(roomId).emit('roomInfo', {
  action: 'join'
});        

Could you confirm that it solves your problem?

loongmxbt commented 3 years ago

Thank you very much! Changing socket.to into io.to solves the problem! I need to watch the docs more carefully.