0

代码如下,它是go-libp2p的官方演示。我没有遇到任何其他引用或未定义的错误

    // if a remote peer has been passed on the command line, connect to it
    // and send it 5 ping messages, otherwise wait for a signal to stop
    if len(os.Args) > 1 {
        addr, err := multiaddr.NewMultiaddr(os.Args[1])
        if err != nil {
            panic(err)
        }
        peer, err := peerstore.AddrInfoFromP2pAddr(addr)
        if err != nil {
            panic(err)
        }
        if err := node.Connect(ctx, *peer); err != nil {
            panic(err)
        }
        fmt.Println("sending 5 ping messages to", addr)

导入如下:

import (
    "fmt"
    "os"
    "os/signal"
    "syscall"

    "github.com/libp2p/go-libp2p"
    peerstore "github.com/libp2p/go-libp2p-core/peer"
    "github.com/libp2p/go-libp2p/p2p/protocol/ping"
    multiaddr "github.com/multiformats/go-multiaddr"
)
4

1 回答 1

1

看起来您正在关注“入门”教程。您需要导入context问题中的代码块之前,您需要创建一个上下文:

// create context
ctx:=context.Background()

// if a remote peer has been passed on the command line, connect to it
// and send it 5 ping messages, otherwise wait for a signal to stop
if len(os.Args) > 1 {
    addr, err := multiaddr.NewMultiaddr(os.Args[1])
    if err != nil {
        panic(err)
    }
    peer, err := peerstore.AddrInfoFromP2pAddr(addr)
    if err != nil {
        panic(err)
    }
    if err := node.Connect(ctx, *peer); err != nil {
        panic(err)
    }
    fmt.Println("sending 5 ping messages to", addr)
于 2022-01-02T11:43:06.200 回答