Fixed websocket sending once again.

This commit is contained in:
Sascha L. Teichmann 2022-03-03 22:30:06 +01:00
parent c87ce03dbe
commit 0968c5c07c
2 changed files with 10 additions and 11 deletions

View File

@ -26,10 +26,10 @@ type connection struct {
type ( type (
tilesMsg struct { tilesMsg struct {
Tiles []xz `json:"tiles,omitempty"` Tiles []xz `json:"tiles"`
} }
plsMsg struct { plsMsg struct {
Pls []*player `json:"players,omitempty"` Pls []*player `json:"players"`
} }
) )
@ -83,8 +83,6 @@ func (wsf *websocketForwarder) send(m interface{}) {
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:

View File

@ -133,9 +133,7 @@ func samePlayers(a, b []*player) bool {
func (ps *players) run() { func (ps *players) run() {
for { for {
ps.mu.Lock() empty := len(ps.current()) == 0
empty := len(ps.pls) == 0
ps.mu.Unlock()
pls, err := ps.readFromFIFO() pls, err := ps.readFromFIFO()
if err != nil { if err != nil {
@ -169,12 +167,15 @@ func (ps *players) run() {
} }
} }
func (ps *players) current() []*player {
ps.mu.RLock()
defer ps.mu.RUnlock()
return ps.pls
}
func (ps *players) ServeHTTP(rw http.ResponseWriter, r *http.Request) { func (ps *players) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
rw.Header().Set("Content-Type", "application/json") rw.Header().Set("Content-Type", "application/json")
var pls []*player pls := ps.current()
ps.mu.RLock()
pls = ps.pls
ps.mu.RUnlock()
encoder := json.NewEncoder(rw) encoder := json.NewEncoder(rw)
if err := encoder.Encode(pls); err != nil { if err := encoder.Encode(pls); err != nil {
log.Printf("error: sending JSON failed: %s\n", err) log.Printf("error: sending JSON failed: %s\n", err)