-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathleader.go
executable file
·56 lines (45 loc) · 1.14 KB
/
leader.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
package main
import (
"encoding/json"
"flag"
"fmt"
"math/rand"
"net"
"time"
"kitty/node"
)
func main() {
port := flag.String("port", "8001", "Port to run this node on, default 8001")
flag.Parse()
rand.Seed(time.Now().UTC().UnixNano())
currentNodeID := rand.Intn(2048)
currentNodeIP, _ := net.InterfaceAddrs()
currentNode := node.Node{
ID: currentNodeID,
IPAddress: currentNodeIP[0].String(),
Port: *port,
}
fmt.Printf("Leader Node Started. Followers can connect to %v:%v\n", currentNode.IPAddress, currentNode.Port)
startLeaderNode(currentNode)
}
func startLeaderNode(currentNode node.Node) {
listener, err := net.Listen("tcp", fmt.Sprint(":"+currentNode.Port))
if err != nil {
fmt.Println("Port is already in use!")
} else {
for {
inboundConnection, err := listener.Accept()
if err != nil {
if _, success := err.(net.Error); success {
fmt.Println("Error on listen", currentNode.ID)
return
}
} else {
var requestMessage node.Message
json.NewDecoder(inboundConnection).Decode(&requestMessage)
fmt.Println(requestMessage.Message)
inboundConnection.Close()
}
}
}
}