musique/server/musique-bridge.go

71 lines
1.2 KiB
Go
Raw Normal View History

2022-12-05 22:34:40 +01:00
package main
import (
"C"
2022-12-09 16:05:25 +01:00
"bufio"
2022-12-05 22:34:40 +01:00
"fmt"
"net"
2022-12-09 16:05:25 +01:00
"strings"
2022-12-09 16:12:33 +01:00
"sync"
"time"
2022-12-05 22:34:40 +01:00
)
2022-12-09 16:05:25 +01:00
var clients []client
var pinger chan struct{}
2022-12-05 22:34:40 +01:00
//export ServerInit
func ServerInit() {
2022-12-09 16:05:25 +01:00
// scanResult = scan()
pinger = make(chan struct{}, 100)
2022-12-09 16:12:33 +01:00
waitForConnection := sync.WaitGroup{}
waitForConnection.Add(1)
2022-12-09 16:05:25 +01:00
go func() {
l, err := net.Listen("tcp", ":8081")
if err != nil {
return
}
defer l.Close()
2022-12-09 16:12:33 +01:00
waitForConnection.Done()
2022-12-09 16:05:25 +01:00
for {
conn, err := l.Accept()
if err != nil {
continue
}
go func(c net.Conn) {
defer c.Close()
s := bufio.NewScanner(c)
for s.Scan() {
response := s.Text()
if response == "time" {
fmt.Fprintln(conn, time.Now().UnixMilli())
continue
}
if strings.HasPrefix(response, "start") {
startTimeString := strings.TrimSpace(response[len("start"):])
startTime := int64(0)
fmt.Sscanf(startTimeString, "%d", &startTime)
time.Sleep(time.Duration(startTime) * time.Millisecond)
pinger <- struct{}{}
continue
}
}
}(conn)
}
}()
2022-12-09 16:12:33 +01:00
waitForConnection.Wait()
scanResult := []string{} // scan()
2022-12-09 16:12:33 +01:00
clients = timesync(scanResult)
2022-12-05 22:34:40 +01:00
}
//export ServerBeginProtocol
func ServerBeginProtocol() {
2022-12-09 16:05:25 +01:00
self := notifyAll(clients)
select {
case <-self:
case <-pinger:
2022-12-05 22:34:40 +01:00
}
}