forked from thusharprakash/p2p-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
73 lines (60 loc) · 1.58 KB
/
main.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
73
// Description: This is a simple chat application that uses the P2P library to create a chat room and send messages to other peers in the room.
package main
import (
"bufio"
"context"
"flag"
"fmt"
"os"
"strings"
"p2p-sdk/p2p"
)
func main() {
// parse some flags to set our nickname and the room to join
nickFlag := flag.String("nick", "", "nickname to use in chat. will be generated if empty")
roomFlag := flag.String("room", "example-room", "name of chat room to join")
flag.Parse()
ctx := context.Background()
// Initialize the P2P library
p2pInstance, err := p2p.NewP2P(ctx)
if err != nil {
panic(err)
}
// use the nickname from the cli flag, or a default if blank
nick := *nickFlag
if len(nick) == 0 {
nick = p2p.DefaultNick(p2pInstance.Host.ID())
}
// join the room from the cli flag, or the flag default
roomName := *roomFlag
// Join an event room
room, err := p2pInstance.JoinRoom(ctx, roomName, nick)
if err != nil {
panic(err)
}
// Listen for incoming messages
go func() {
for msg := range room.Messages {
fmt.Printf("[%s] %s: %s\n", roomName, msg.SenderNick, msg.Message)
}
}()
// Read user input from stdin and publish to the room
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
text := scanner.Text()
if strings.TrimSpace(text) == "" {
continue
}
if text == "/quit" {
break
}
if err := room.Publish(text); err != nil {
fmt.Printf("Error publishing message: %s\n", err)
}
}
if err := scanner.Err(); err != nil {
fmt.Printf("Error reading from stdin: %s\n", err)
}
// Keep the main function running
select {}
}