github.com/gnolang/gno@v0.0.0-20240520182011-228e9d0192ce/tm2/pkg/p2p/cmd/stest/main.go (about) 1 package main 2 3 import ( 4 "bufio" 5 "flag" 6 "fmt" 7 "net" 8 "os" 9 10 "github.com/gnolang/gno/tm2/pkg/crypto/ed25519" 11 p2pconn "github.com/gnolang/gno/tm2/pkg/p2p/conn" 12 ) 13 14 var ( 15 remote string 16 listen string 17 ) 18 19 func init() { 20 flag.StringVar(&listen, "listen", "", "set to :port if server, eg :8080") 21 flag.StringVar(&remote, "remote", "", "remote ip:port") 22 flag.Parse() 23 } 24 25 func main() { 26 if listen != "" { 27 fmt.Println("listening at", listen) 28 ln, err := net.Listen("tcp", listen) 29 if err != nil { 30 // handle error 31 } 32 conn, err := ln.Accept() 33 if err != nil { 34 panic(err) 35 } 36 handleConnection(conn) 37 } else { 38 // connect to remote. 39 if remote == "" { 40 panic("must specify remote ip:port unless server") 41 } 42 fmt.Println("connecting to", remote) 43 conn, err := net.Dial("tcp", remote) 44 if err != nil { 45 panic(err) 46 } 47 handleConnection(conn) 48 } 49 } 50 51 func handleConnection(conn net.Conn) { 52 priv := ed25519.GenPrivKey() 53 pub := priv.PubKey() 54 fmt.Println("local pubkey:", pub) 55 fmt.Println("local pubkey addr:", pub.Address()) 56 57 sconn, err := p2pconn.MakeSecretConnection(conn, priv) 58 if err != nil { 59 panic(err) 60 } 61 // Read line from sconn and print. 62 go func() { 63 sc := bufio.NewScanner(sconn) 64 for sc.Scan() { 65 line := sc.Text() // GET the line string 66 fmt.Println(">>", line) 67 } 68 if err := sc.Err(); err != nil { 69 panic(err) 70 } 71 }() 72 // Read line from stdin and write. 73 for { 74 sc := bufio.NewScanner(os.Stdin) 75 for sc.Scan() { 76 line := sc.Text() + "\n" 77 _, err := sconn.Write([]byte(line)) 78 if err != nil { 79 panic(err) 80 } 81 } 82 if err := sc.Err(); err != nil { 83 panic(err) 84 } 85 } 86 }