zishang520/socket.io

Cannot find a way to successfully broadcast

CodaBool opened this issue · 3 comments

❓Broadcast

I see in the source code there is a method exposed for this. It just does not seem to work.

this just ends up working like a regular emit

client.Broadcast().To(ROOM).Emit("hi")

I also saw that adapter has a broadcast. However, I get nil errors with this one.

nil error

io.Sockets().Adapter().Broadcast(&parser.Packet{
    Type: parser.EVENT,
    Data: "hi",
}, &server.BroadcastOptions{
    Rooms: types.NewSet(ROOM),
})

The repository is awesome I have been enjoying it greatly 😎

Hi this code snippet is a simple broadcast example:

custom := io.Of(
	regexp.MustCompile(`/\w+`),
	nil,
)
custom.On("connection", func(clients ...interface{}) {
	socket := clients[0].(*socket.Socket)
	socket.Broadcast().Emit("Broadcast", "To all connected clients except the sender")
	custom.Emit("Broadcast", "broadcast to namespace \\w+ matches")
	io.Emit("Broadcast", "broadcast to the default namespace /")
})

Of course, you can also refer to the socket.io documentation. The usage of this project is similar to socket.io of nodejs

nice, I have that code snippet working for broadcasting.

For some reason though after leaving and entering a room, broadcast seems to no longer work. Which was why I thought it was something wrong with broadcast. It seems to be more likely that I am leaving and joining a room wrong.

an example

// this will have a client leave their room and join all other existing rooms
// once joining it will make a broadcast to that room
// obviously a weird thing to do
// but I am just trying to prove in a simple way that a client is sharing a room
io.Sockets().Adapter().Rooms().Range(func(sid, value interface{}) bool {

  // skip over your own room
  if socket.Room(client.Id()) != sid.(socket.Room) {

    // prints all rooms
    io.Sockets().Adapter().Rooms().Range(func(room, value interface{}) bool {
      log.Print("  - ", room)
      return true
    })

    log.Print(fmt.Sprintf("%v ➡️  %v", socket.Id(), sid)))

    // leave current room and join a room it found another client on
    client.Leave(socket.Room(socket.Id()))
    client.Join(sid.(socket.Room))

    // prints all rooms
    io.Sockets().Adapter().Rooms().Range(func(room, value interface{}) bool {
      log.Print("  - ", room)
      return true
    })

    client.Broadcast().To(sid.(socket.Room)).Emit("chat", "hi")
  }
  return true
})

there is only one room on the server
img1

despite both clients being the same room, they both receive the broadcast emit
img2

oh sorry Looks like I should have followed the socket.io docs behavior more. I commented out the socket.Leave(server.Room(socket.Id())) line and it works as expected. I don't think there is anything wrong with your repo. I will close this issue.