homecontroller/main.go

55 lines
1.0 KiB
Go

package main
import (
"encoding/json"
"errors"
"log"
"net"
"os"
)
var clients []*Device
var storedClients []StoredClient
func main() {
clients = make([]*Device, 0)
data, err := os.ReadFile("clients.json")
if err != nil {
panic(err)
}
err = json.Unmarshal(data, &storedClients)
if err != nil {
panic(err)
}
// Create a connection to the server
addr, err := net.ResolveTCPAddr("tcp", "0.0.0.0")
if err != nil {
log.Fatal("Error resolving address " + err.Error())
}
listen, err := net.ListenTCP("tcp", addr)
if err != nil {
log.Fatal(err)
}
// close listener
defer func(listen *net.TCPListener) {
_ = listen.Close()
}(listen)
go func() {
for {
conn, err := listen.AcceptTCP()
if err != nil {
var opErr *net.OpError
if errors.As(err, &opErr) && opErr.Err.Error() == "use of closed network connection" {
log.Println("Listener closed, stopping server.")
return
}
log.Println("Error accepting connection:", err)
continue
}
go handleRequest(conn)
}
}()
}