M main.go => main.go +7 -15
@@ 15,7 15,6 @@ import (
"github.com/ipfs/go-log"
"github.com/libp2p/go-libp2p"
"github.com/libp2p/go-libp2p-core/host"
- "github.com/libp2p/go-libp2p-core/network"
"github.com/libp2p/go-libp2p-core/peer"
"github.com/libp2p/go-libp2p-core/protocol"
dht "github.com/libp2p/go-libp2p-kad-dht"
@@ 54,18 53,6 @@ func (eo ElectionOption) Equals(other merkletree.Content) (bool, error) {
return string(eo) == string(other.(ElectionOption)), nil
}
-func masterStreamHandler(stream network.Stream) {
- Logger.Info("got a new stream!")
- writer := bufio.NewWriter(stream)
-
- for _, option := range electionOptions {
- writer.WriteString(fmt.Sprintf("%s\n", option))
- }
-
- writer.Flush()
- stream.Close()
-}
-
func createElection() {
var form *tview.Form
n := 3
@@ 202,13 189,18 @@ func bootstrap() {
} else { // we are a slave
Logger.Info("attempting to open stream with master peer...")
stream, err := h.NewStream(ctx, masterID, ProtocolID)
+ rw := bufio.NewReadWriter(bufio.NewReader(stream), bufio.NewWriter(stream))
if err != nil {
panic(err)
}
Logger.Info("opened stream with master peer")
- reader := bufio.NewReader(stream)
+ _, err = rw.WriteString("options\n")
+ if err != nil {
+ panic(err)
+ }
+ rw.Flush()
for {
- str, err := reader.ReadString('\n')
+ str, err := rw.ReadString('\n')
if err == io.EOF {
break
} else if err != nil {
A master.go => master.go +37 -0
@@ 0,0 1,37 @@
+package main
+
+import (
+ "bufio"
+ "fmt"
+ "io"
+
+ "github.com/libp2p/go-libp2p-core/network"
+)
+
+func handleMasterCmd(cmd string, writer *bufio.Writer) {
+ switch cmd {
+ case "options":
+ for _, option := range electionOptions {
+ writer.WriteString(fmt.Sprintf("%s\n", option))
+ }
+
+ writer.Flush()
+ }
+}
+
+func masterStreamHandler(stream network.Stream) {
+ Logger.Info("got a new stream!")
+ rw := bufio.NewReadWriter(bufio.NewReader(stream), bufio.NewWriter(stream))
+
+ cmd, err := rw.ReadString('\n')
+ if err != nil && err != io.EOF {
+ panic(err)
+ }
+ if cmd[len(cmd)-1] == '\n' {
+ cmd = cmd[:len(cmd)-1]
+ }
+
+ fmt.Println(cmd)
+ handleMasterCmd(cmd, rw.Writer)
+ stream.Close()
+}