diff --git a/cmd/mtwebmapper/forwardupdates.go b/cmd/mtwebmapper/forwardupdates.go index ec40ab3..394a1c6 100644 --- a/cmd/mtwebmapper/forwardupdates.go +++ b/cmd/mtwebmapper/forwardupdates.go @@ -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() } diff --git a/cmd/mtwebmapper/main.go b/cmd/mtwebmapper/main.go index 64c465f..901434f 100644 --- a/cmd/mtwebmapper/main.go +++ b/cmd/mtwebmapper/main.go @@ -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) } diff --git a/cmd/mtwebmapper/players.go b/cmd/mtwebmapper/players.go index e48aa39..97ad56e 100644 --- a/cmd/mtwebmapper/players.go +++ b/cmd/mtwebmapper/players.go @@ -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()