conn_room.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. package neffos
  2. import (
  3. "context"
  4. )
  5. // Room describes a connected connection to a room,
  6. // emits messages with the `Message.Room` filled to the specific room
  7. // and `Message.Namespace` to the underline `NSConn`'s namespace.
  8. type Room struct {
  9. NSConn *NSConn
  10. Name string
  11. }
  12. func newRoom(ns *NSConn, roomName string) *Room {
  13. return &Room{
  14. NSConn: ns,
  15. Name: roomName,
  16. }
  17. }
  18. // String method simply returns the Conn's ID().
  19. // To get the room's name simply use the `Room.Name` struct field instead.
  20. // Useful method to this room to be passed on `Server#Broadcast` method
  21. // to exclude itself from the broadcasted message's receivers.
  22. func (r *Room) String() string {
  23. return r.NSConn.String()
  24. }
  25. // Emit method sends a message to the remote side with its `Message.Room` filled to this specific room
  26. // and `Message.Namespace` to the underline `NSConn`'s namespace.
  27. func (r *Room) Emit(event string, body []byte) bool {
  28. return r.NSConn.Conn.Write(Message{
  29. Namespace: r.NSConn.namespace,
  30. Room: r.Name,
  31. Event: event,
  32. Body: body,
  33. })
  34. }
  35. // Leave method sends a remote and local leave room signal `OnRoomLeave` to this specific room
  36. // and fires the `OnRoomLeft` event if succeed.
  37. func (r *Room) Leave(ctx context.Context) error {
  38. return r.NSConn.askRoomLeave(ctx, Message{
  39. Namespace: r.NSConn.namespace,
  40. Room: r.Name,
  41. Event: OnRoomLeave,
  42. }, true)
  43. }