# Libp2p chat application ## Chat ! 1. Clone ```bash git clone https://github.com/libp2p/go-libp2p cd go-libp2p/examples/pubsub/basic-chat-with-rendezvous ``` 2. Build and run the binary ```bash go run . # or, build and run separately go build . ./chat ``` 程式碼講解: ```go func main() { flag.Parse() ctx := context.Background() h, err := libp2p.New(libp2p.ListenAddrStrings("/ip4/0.0.0.0/tcp/0")) if err != nil { panic(err) } go discoverPeers(ctx, h) // 建立 DHT,與其他節點建立連結 ps, err := pubsub.NewGossipSub(ctx, h) // 回傳 Pucsub 物件 if err != nil { panic(err) } topic, err := ps.Join(*topicNameFlag) // 加入 Topic ,一個 topic 只會有一個 topic handler if err != nil { panic(err) } go streamConsoleTo(ctx, topic) // 無限迴圈等節點打字 sub, err := topic.Subscribe() if err != nil { panic(err) } printMessagesFrom(ctx, sub) // 無限迴圈,等 message channel 有新訊息將其打印出來 } ```
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up