golibp2pgo-libp2p

Why two stream are required when connecting nodes with libp2p? When handler is called after the peer is connected?


I am following this example - https://github.com/libp2p/go-libp2p/tree/master/examples/chat-with-mdns

Here we are initiating a node and using mdns for discovering other nodes on the same local network.

I am a bit confused about the connection lifecycle.

First, we create a host with handler set

func handleStream(stream network.Stream) {
    fmt.Println("Got a new stream!")

    // Create a buffer stream for non-blocking read and write.
    rw := bufio.NewReadWriter(bufio.NewReader(stream), bufio.NewWriter(stream))

    go readData(rw)
    go writeData(rw)

    // 'stream' will stay open until you close it (or the other side closes it).
}    

func main() {
    host, err := libp2p.Newlibp2p.ListenAddrs(sourceMultiAddr),libp2p.Identity(prvKey), )
        host.SetStreamHandler(protocol.ID(cfg.ProtocolID), handleStream)

}

When is this handleStream function called?

After this we search for peer and after finding peer we connect to peer and create another stream to read and write.

    if err := host.Connect(ctx, peer); err != nil {
        fmt.Println("Connection failed:", err)
        continue
    }

    // open a stream, this stream will be handled by handleStream other end
    stream, err := host.NewStream(ctx, peer.ID, protocol.ID(cfg.ProtocolID))

    if err != nil {
        fmt.Println("Stream open failed", err)
    } else {
        rw := bufio.NewReadWriter(bufio.NewReader(stream), bufio.NewWriter(stream))

        go writeData(rw)
        go readData(rw, "client")
        fmt.Println("Connected to:", peer)
    }

I don't understand why we have two streams to read and write. Why not the handler function enough for reading and writing? Why not the handler called just after being connected to the node?

Any help is appreciated.


Solution

  • https://github.com/libp2p/go-libp2p/issues/2418 - seems like the example has implementation issues. There is no need of two stream from both the peers. Only one stream is enough from one peer for each peer.

    handler is called when peer starts sending data.