diff options
| -rw-r--r-- | internal/quorum.go | 11 | ||||
| -rw-r--r-- | internal/run.go | 26 | ||||
| -rw-r--r-- | internal/tcpserver.go | 60 | ||||
| -rw-r--r-- | internal/vote.go | 9 |
4 files changed, 104 insertions, 2 deletions
diff --git a/internal/quorum.go b/internal/quorum.go new file mode 100644 index 0000000..528f460 --- /dev/null +++ b/internal/quorum.go @@ -0,0 +1,11 @@ +package internal + +import "time" + +type quorum struct { + ID string + Age time.Duration + Votes int +} + +type quorumMap map[string]quorum diff --git a/internal/run.go b/internal/run.go index 2d177ea..4904d33 100644 --- a/internal/run.go +++ b/internal/run.go @@ -1,10 +1,32 @@ package internal -import "context" +import ( + "context" + "fmt" + "log" +) func Run(ctx context.Context, configFile string) { - _, err := newConfig(configFile) + config, err := newConfig(configFile) if err != nil { panic(err) } + + ch := make(chan vote) + + go func() { + for { + select { + case vote := <-ch: + log.Println(vote) + case <-ctx.Done(): + return + } + } + }() + + address := fmt.Sprintf("%s:%d", config.Hostname, config.Port) + if err := startTcpServer(ctx, address, ch); err != nil { + panic(err) + } } diff --git a/internal/tcpserver.go b/internal/tcpserver.go new file mode 100644 index 0000000..f264d9e --- /dev/null +++ b/internal/tcpserver.go @@ -0,0 +1,60 @@ +package internal + +import ( + "bufio" + "context" + "fmt" + "log" + "net" + "time" +) + +func startTcpServer(ctx context.Context, address string, ch chan<- vote) error { + listener, err := net.Listen("tcp", address) + if err != nil { + return fmt.Errorf("Error starting TCP server: %s", err.Error()) + } + defer listener.Close() + + log.Printf("TCP server started on %s\n", address) + + for { + // Accept incoming client connections + conn, err := listener.Accept() + if err != nil { + log.Printf("Error accepting connection: %s\n", err.Error()) + continue + } + + log.Printf("Client connected: %s\n", conn.RemoteAddr().String()) + + // Handle the connection in a new goroutine + go handleConnection(ctx, conn, ch) + } +} + +func handleConnection(ctx context.Context, conn net.Conn, ch chan<- vote) { + defer conn.Close() + remoteAddr := conn.RemoteAddr().String() + log.Printf("Client %s connected\n", remoteAddr) + + reader := bufio.NewReader(conn) + for { + select { + case <-ctx.Done(): + log.Printf("Server context done, disconnecting client %s\n", remoteAddr) + return + default: + message, err := reader.ReadString('\n') + if err != nil { + log.Printf("Client %s disconnected: %s\n", remoteAddr, err.Error()) + break + } + + log.Printf("Received message from %s: %s", remoteAddr, message) + ch <- vote{From: remoteAddr, time: time.Now()} + + conn.Write([]byte(message)) + } + } +} diff --git a/internal/vote.go b/internal/vote.go new file mode 100644 index 0000000..7c7268a --- /dev/null +++ b/internal/vote.go @@ -0,0 +1,9 @@ +package internal + +import "time" + +type vote struct { + From string + //IDs []string + time time.Time +} |
