/
protocol.go
72 lines (66 loc) · 1.52 KB
/
protocol.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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package main
import (
"bufio"
"context"
"fmt"
"io"
"os"
"github.com/libp2p/go-libp2p/core/host"
"github.com/libp2p/go-libp2p/core/network"
)
const chatProtocol = "/libp2p/chat/1.0.0"
// TODO: Replace this handler with a function that handles message from a
// pubsub Subscribe channel.
func chatHandler(s network.Stream) {
data, err := io.ReadAll(s)
if err != nil {
fmt.Fprintln(os.Stderr, err)
}
fmt.Println("Received:", string(data))
}
// TODO: Replace this with a send function that publishes the string messages
// on our pubsub topic.
func chatSend(msg string, s network.Stream) error {
fmt.Println("Sending:", msg)
w := bufio.NewWriter(s)
n, err := w.WriteString(msg)
if n != len(msg) {
return fmt.Errorf("expected to write %d bytes, wrote %d", len(msg), n)
}
if err != nil {
return err
}
if err = w.Flush(); err != nil {
return err
}
s.Close()
data, err := io.ReadAll(s)
if err != nil {
return err
}
if len(data) > 0 {
fmt.Println("Received:", string(data))
}
return nil
}
func chatInputLoop(ctx context.Context, h host.Host, donec chan struct{}) {
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
msg := scanner.Text()
for _, peer := range h.Network().Peers() {
if _, err := h.Peerstore().SupportsProtocols(peer, chatProtocol); err == nil {
s, err := h.NewStream(ctx, peer, chatProtocol)
defer func() {
if err != nil {
fmt.Fprintln(os.Stderr, err)
}
}()
if err != nil {
continue
}
err = chatSend(msg, s)
}
}
}
donec <- struct{}{}
}