forked from libp2p/go-libp2p
-
Notifications
You must be signed in to change notification settings - Fork 0
/
protocol.go
46 lines (43 loc) · 876 Bytes
/
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
package main
import (
"bufio"
"context"
"crypto/rand"
"fmt"
"os"
"time"
"github.com/gogo/protobuf/proto"
pubsub "github.com/libp2p/go-libp2p-pubsub"
)
func chatInputLoop(ctx context.Context, topic *pubsub.Topic, donec chan struct{}) {
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
msg := scanner.Text()
msgId := make([]byte, 10)
_, err := rand.Read(msgId)
if err != nil {
fmt.Fprintln(os.Stderr, err)
continue
}
now := time.Now().Unix()
req := &Request{
Type: Request_SEND_MESSAGE.Enum(),
SendMessage: &SendMessage{
Id: msgId,
Data: []byte(msg),
Created: &now,
},
}
msgBytes, err := proto.Marshal(req)
if err != nil {
fmt.Fprintln(os.Stderr, err)
continue
}
err = topic.Publish(ctx, msgBytes)
if err != nil {
fmt.Fprintln(os.Stderr, err)
continue
}
}
donec <- struct{}{}
}