Send players to websocket on connect.

This commit is contained in:
Sascha L. Teichmann 2022-03-03 22:57:02 +01:00
parent 0968c5c07c
commit 449741db4c
3 changed files with 39 additions and 8 deletions

View File

@ -5,7 +5,6 @@
package main
import (
"bytes"
"encoding/json"
"log"
"net/http"
@ -17,6 +16,7 @@ type websocketForwarder struct {
upgrader *websocket.Upgrader
connections map[*connection]struct{}
funcs chan func(*websocketForwarder)
init func(*websocketForwarder, *connection)
}
type connection struct {
@ -67,22 +67,24 @@ func (wsf *websocketForwarder) unregister(c *connection) {
}
}
func (wsf *websocketForwarder) setInit(init func(*websocketForwarder, *connection)) {
wsf.funcs <- func(wsf *websocketForwarder) {
wsf.init = init
}
}
func (wsf *websocketForwarder) send(m interface{}) {
wsf.funcs <- func(wsf *websocketForwarder) {
if len(wsf.connections) == 0 {
return
}
var buf bytes.Buffer
encoder := json.NewEncoder(&buf)
if err := encoder.Encode(m); err != nil {
log.Printf("encoding changes failed: %s\n", err)
data, err := json.Marshal(m)
if err != nil {
log.Printf("encoding failed. %v\n", err)
return
}
data := buf.Bytes()
for c := range wsf.connections {
select {
case c.send <- data:
@ -94,6 +96,26 @@ func (wsf *websocketForwarder) send(m interface{}) {
}
}
func (wsf *websocketForwarder) singleSend(c *connection, m interface{}) {
wsf.funcs <- func(wsf *websocketForwarder) {
_, ok := wsf.connections[c]
if !ok {
return
}
data, err := json.Marshal(m)
if err != nil {
log.Printf("encoding failed. %v\n", err)
return
}
select {
case c.send <- data:
default:
delete(wsf.connections, c)
close(c.send)
}
}
}
func (wsf *websocketForwarder) BaseTilesUpdated(changes []xz) {
wsf.send(&tilesMsg{Tiles: changes})
}
@ -112,6 +134,9 @@ func (wsf *websocketForwarder) ServeHTTP(rw http.ResponseWriter, r *http.Request
wsf.register(c)
defer wsf.unregister(c)
go c.writer()
if wsf.init != nil {
wsf.init(wsf, c)
}
c.reader()
}

View File

@ -59,7 +59,9 @@ func main() {
if cfg.PlayersFIFO != "" {
plys := newPlayers(cfg.PlayersFIFO, wsf)
wsf.setInit(plys.initConnection)
go plys.run()
router.Path("/players").Methods("GET").Handler(plys)
}

View File

@ -173,6 +173,10 @@ func (ps *players) current() []*player {
return ps.pls
}
func (ps *players) initConnection(wsf *websocketForwarder, c *connection) {
wsf.singleSend(c, &plsMsg{Pls: ps.current()})
}
func (ps *players) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
rw.Header().Set("Content-Type", "application/json")
pls := ps.current()