send empty players array if no player is online any more.

This commit is contained in:
Sascha L. Teichmann 2022-03-03 20:22:37 +01:00
parent f533ed71e7
commit c87ce03dbe
2 changed files with 16 additions and 7 deletions

View File

@ -24,10 +24,14 @@ type connection struct {
send chan []byte send chan []byte
} }
type msg struct { type (
Tiles []xz `json:"tiles,omitempty"` tilesMsg struct {
Pls []*player `json:"players,omitempty"` Tiles []xz `json:"tiles,omitempty"`
} }
plsMsg struct {
Pls []*player `json:"players,omitempty"`
}
)
func newWebsocketForwarder() *websocketForwarder { func newWebsocketForwarder() *websocketForwarder {
upgrader := &websocket.Upgrader{ upgrader := &websocket.Upgrader{
@ -63,7 +67,7 @@ func (wsf *websocketForwarder) unregister(c *connection) {
} }
} }
func (wsf *websocketForwarder) send(m *msg) { func (wsf *websocketForwarder) send(m interface{}) {
wsf.funcs <- func(wsf *websocketForwarder) { wsf.funcs <- func(wsf *websocketForwarder) {
if len(wsf.connections) == 0 { if len(wsf.connections) == 0 {
return return
@ -79,6 +83,8 @@ func (wsf *websocketForwarder) send(m *msg) {
data := buf.Bytes() data := buf.Bytes()
log.Printf("sending: %s\n", string(data))
for c := range wsf.connections { for c := range wsf.connections {
select { select {
case c.send <- data: case c.send <- data:
@ -91,11 +97,11 @@ func (wsf *websocketForwarder) send(m *msg) {
} }
func (wsf *websocketForwarder) BaseTilesUpdated(changes []xz) { func (wsf *websocketForwarder) BaseTilesUpdated(changes []xz) {
wsf.send(&msg{Tiles: changes}) wsf.send(&tilesMsg{Tiles: changes})
} }
func (wsf *websocketForwarder) BroadcastPlayers(pls []*player) { func (wsf *websocketForwarder) BroadcastPlayers(pls []*player) {
wsf.send(&msg{Pls: pls}) wsf.send(&plsMsg{Pls: pls})
} }
func (wsf *websocketForwarder) ServeHTTP(rw http.ResponseWriter, r *http.Request) { func (wsf *websocketForwarder) ServeHTTP(rw http.ResponseWriter, r *http.Request) {

View File

@ -160,6 +160,9 @@ func (ps *players) run() {
} }
ps.mu.Unlock() ps.mu.Unlock()
if change && ps.wsf != nil { if change && ps.wsf != nil {
if pls == nil {
pls = []*player{}
}
// TODO: Throttle this! // TODO: Throttle this!
ps.wsf.BroadcastPlayers(pls) ps.wsf.BroadcastPlayers(pls)
} }