main.go
1 // Simple libp2p QUIC server for testing 2 // Run: go run main.go 3 package main 4 5 import ( 6 "context" 7 "fmt" 8 "log" 9 "os" 10 "os/signal" 11 "syscall" 12 13 "github.com/libp2p/go-libp2p" 14 "github.com/libp2p/go-libp2p/core/network" 15 "github.com/libp2p/go-libp2p/core/peer" 16 "github.com/multiformats/go-multiaddr" 17 ) 18 19 func main() { 20 ctx, cancel := context.WithCancel(context.Background()) 21 defer cancel() 22 23 // Create a libp2p host with QUIC transport only 24 host, err := libp2p.New( 25 libp2p.ListenAddrStrings( 26 "/ip4/0.0.0.0/udp/4001/quic-v1", 27 ), 28 // Disable other transports 29 libp2p.Transport(libp2p.QUICTransport), 30 ) 31 if err != nil { 32 log.Fatalf("Failed to create host: %v", err) 33 } 34 defer host.Close() 35 36 // Print listening addresses 37 fmt.Println("libp2p QUIC server started!") 38 fmt.Printf("Peer ID: %s\n", host.ID()) 39 fmt.Println("Listening on:") 40 for _, addr := range host.Addrs() { 41 fmt.Printf(" %s/p2p/%s\n", addr, host.ID()) 42 } 43 fmt.Println() 44 45 // Set up a simple ping handler 46 host.SetStreamHandler("/ipfs/ping/1.0.0", func(s network.Stream) { 47 log.Printf("Got ping from %s", s.Conn().RemotePeer()) 48 defer s.Close() 49 // Echo back 50 buf := make([]byte, 32) 51 for { 52 n, err := s.Read(buf) 53 if err != nil { 54 return 55 } 56 s.Write(buf[:n]) 57 } 58 }) 59 60 // Log connection events 61 host.Network().Notify(&network.NotifyBundle{ 62 ConnectedF: func(n network.Network, c network.Conn) { 63 log.Printf("Connected: %s (%s)", c.RemotePeer(), c.RemoteMultiaddr()) 64 }, 65 DisconnectedF: func(n network.Network, c network.Conn) { 66 log.Printf("Disconnected: %s", c.RemotePeer()) 67 }, 68 }) 69 70 fmt.Println("Waiting for connections... (Ctrl+C to stop)") 71 72 // Wait for interrupt 73 sigCh := make(chan os.Signal, 1) 74 signal.Notify(sigCh, syscall.SIGINT, syscall.SIGTERM) 75 <-sigCh 76 77 fmt.Println("\nShutting down...") 78 }