forked from RoboCup-SSL/ssl-game-controller
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ciServer.go
64 lines (54 loc) · 1.25 KB
/
ciServer.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package rcon
import (
"bufio"
"encoding/binary"
"github.com/RoboCup-SSL/ssl-game-controller/pkg/refproto"
"github.com/RoboCup-SSL/ssl-go-tools/pkg/sslconn"
"log"
"net"
"time"
)
type CiServer struct {
TimeConsumer CiTimeConsumer
}
type CiTimeConsumer func(time.Time) *refproto.Referee
func NewCiServer() CiServer {
return CiServer{}
}
func (s *CiServer) Listen(address string) {
listener, err := net.Listen("tcp", address)
if err != nil {
log.Print("Failed to listen on ", address)
return
}
log.Print("Listening on ", address)
for {
conn, err := listener.Accept()
if err != nil {
log.Print("Could not accept connection: ", err)
} else {
log.Println("CI connection established")
s.serve(conn)
log.Println("CI connection closed")
}
}
}
func (s *CiServer) serve(conn net.Conn) {
defer conn.Close()
for {
reader := bufio.NewReaderSize(conn, 1)
timestamp, err := binary.ReadVarint(reader)
if err != nil {
log.Println("Error reading from CI connection: ", err)
return
}
sec := int64(timestamp / 1e9)
nSec := timestamp - sec*1e9
refMessage := s.TimeConsumer(time.Unix(sec, nSec))
err = sslconn.SendMessage(conn, refMessage)
if err != nil {
log.Printf("Could not send message: %v", err)
return
}
}
}