Skip to content

Commit

Permalink
feat: add websocket api to get online players
Browse files Browse the repository at this point in the history
  • Loading branch information
Emyr298 committed Jun 29, 2024
1 parent 8d11b83 commit 22545e8
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 0 deletions.
14 changes: 14 additions & 0 deletions src/utils/sync_map.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,20 @@ func (s *SyncMap[T, P]) Print() {
log.Println(s.inner_map)
}

func (s *SyncMap[T, P]) Keys() []T {
s.lock.Lock()
defer s.lock.Unlock()
keys := make([]T, len(s.inner_map))

i := 0
for k := range s.inner_map {
keys[i] = k
i++
}

return keys
}

func NewSyncMap[T comparable, P any]() *SyncMap[T, P] {
return &SyncMap[T, P]{
inner_map: make(map[T]P),
Expand Down
11 changes: 11 additions & 0 deletions src/websocket/core/hub.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,10 @@ type PlayerHub struct {
clientToPlayerId *utils.SyncMap[*Client, string]
}

func (hub *PlayerHub) GetAllPlayerId() []string {
return hub.playerIdToClient.Keys()
}

func (hub *PlayerHub) RegisterPlayer(playerId string, client *Client) {
hub.playerIdToClient.Store(playerId, client)
hub.clientToPlayerId.Store(client, playerId)
Expand All @@ -46,6 +50,10 @@ type ClientHub struct {
message chan *MessageWithClient
}

func (hub *ClientHub) GetAllPlayerId() []string {
return hub.playerHub.GetAllPlayerId()
}

func (hub *ClientHub) GetClientFromPlayerId(playerId string) (*Client, bool) {
client, ok := hub.playerHub.playerIdToClient.Load(playerId)
if !ok {
Expand Down Expand Up @@ -120,6 +128,9 @@ func (hub *ClientHub) Run() {
RegisterPlayer: func(playerId string) {
hub.RegisterPlayer(playerId, client)
},
GetPlayerList: func() []string {
return hub.GetAllPlayerId()
},
},
}

Expand Down
1 change: 1 addition & 0 deletions src/websocket/types/interaction.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ type Response struct {
NotifyClient func(message *Message)
NotifyOtherClient func(playerId string, message *Message)
RegisterPlayer func(playerId string)
GetPlayerList func() []string
}

type Interaction struct {
Expand Down

0 comments on commit 22545e8

Please sign in to comment.