summaryrefslogtreecommitdiff
path: root/internal/tcpserver.go
blob: a7153f8f4e6e641347c0a4dcd0ff8235f782ad22 (plain)
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
package internal

import (
	"bufio"
	"context"
	"fmt"
	"log"
	"net"
	"time"
)

func startTcpServer(ctx context.Context, config config, ch chan<- vote) error {
	listener, err := net.Listen("tcp", config.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", config.Address)

	for {
		conn, err := listener.Accept()
		if err != nil {
			log.Printf("Error accepting connection: %s\n", err.Error())
			continue
		}

		if !config.isParticipant(conn.RemoteAddr().String()) {
			log.Printf("Denying connection, peer not a participant: %v\n", conn.RemoteAddr().String())
			conn.Close()
			continue
		}

		log.Printf("Client connected: %s\n", conn.RemoteAddr().String())
		go handleConnection(ctx, conn, ch)
	}
}

func handleConnection(ctx context.Context, conn net.Conn, ch chan<- vote) {
	defer conn.Close()
	remoteAddr := conn.RemoteAddr().String()

	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())
				return
			}

			log.Printf("Received message from %s: %s", remoteAddr, message)
			ch <- vote{From: remoteAddr, time: time.Now()}

			conn.Write([]byte(message))
		}
	}
}