server/spectator.go

64 lines
1.3 KiB
Go
Raw Normal View History

2013-08-19 22:23:35 -07:00
package main
import (
"code.google.com/p/go.net/websocket"
2014-02-16 23:59:17 -08:00
"encoding/json"
"log"
2013-08-19 22:23:35 -07:00
)
type Spectator struct {
2013-08-19 23:44:00 -07:00
ws *websocket.Conn
2013-11-13 22:24:54 -08:00
send chan Message
2014-01-29 22:12:26 -08:00
Id string
2013-08-19 22:23:35 -07:00
}
func (s *Spectator) sender() {
2014-01-29 22:12:26 -08:00
log.Printf("%s: sender launched", s.Id)
2013-08-19 22:23:35 -07:00
for things := range s.send {
2014-02-16 23:59:17 -08:00
b, err := json.Marshal(things)
if err != nil {
break
}
// XXX: send the count to our bandwidth analyzer ...
_, err = s.ws.Write(b)
2013-08-19 22:23:35 -07:00
if err != nil {
break
}
}
s.ws.Close()
2014-01-29 22:12:26 -08:00
log.Printf("%s: spectator sender close", s.Id)
}
func (s *Spectator) recv() {
2014-02-16 23:59:17 -08:00
var msg interface{}
buff := make([]byte, maxMessageSize)
2014-01-29 22:12:26 -08:00
for {
2014-02-16 23:59:17 -08:00
n, err := s.ws.Read(buff)
if err != nil {
log.Printf("%s: problem reading from player: %s", s.Id, err)
break
}
// XXX: send n to our bandwidth analyzer ...
log.Println(string(buff[:n]))
if n == len(buff) {
log.Printf("%s: read buffer overfull: %s", s.Id, string(buff))
break
}
err = json.Unmarshal(buff[:n], &msg)
log.Println(n)
2014-01-29 22:12:26 -08:00
if err != nil {
2014-02-16 23:59:17 -08:00
log.Printf("%s: problem reading from player: %s", s.Id, err)
2014-01-29 22:12:26 -08:00
break
}
2014-02-16 23:59:17 -08:00
// After the first bit of handshaking, the rest of the messages should
// only be "{}" for spectators, and the following could hold true:
//
// if string(buff[:n]) != "{}" {
// log.Printf("protocol breach!!")
// break
// }
2014-01-29 22:12:26 -08:00
}
log.Printf("%s: recv close", s.Id)
s.ws.Close()
2013-08-19 22:23:35 -07:00
}