ChainSafe / js-libp2p-gossipsub

TypeScript implementation of Gossipsub
Apache License 2.0
145 stars 43 forks source link

No recepient after message sent #431

Closed hutianyu2006 closed 1 year ago

hutianyu2006 commented 1 year ago

I know it would be a extremely stupid question, and it is probably my fault, as a newbie for libp2p, but I didn't get any help from neither GhatGPT nor StackOverflow, so I hope I can find any help here.

I merged the piece of example code showed in the Usage section of README.md into the example libp2p-in-the-browser of the js-libp2p repo, and started a dev server. However, I simply didn't find any message published from or to other "peers"(In my case, browser tabs), and when I entered await libp2p.services.pubsub.publish('test', new TextEncoder().encode('This is a test message.')) in the browser console, it returned a {recipients: Array(0)}. If that is my fault, please tell me how should I fix it properly.

Below is the code pieces related to Pubsub services:

import { gossipsub } from '@chainsafe/libp2p-gossipsub'

const libp2p=await createLibp2p({
//<other parts not shown here for brevity>
    services: {
        pubsub: gossipsub({ allowPublishToZeroPeers: true });
    }
})
  libp2p.addEventListener('peer:connect', (evt) => {
    const peerId = evt.detail
        const connections = libp2p.getConnections(evt.detail)
        log(`Connected to ${peerId.toString()}`)
        connections.forEach((conn) => {
            libp2p.services.pubsub.addPeer(conn.remotePeer, conn.stat.direction, conn.remoteAddr)
            libp2p.services.pubsub.subscribe('test')
            libp2p.services.pubsub.publish('test', new TextEncoder().encode('This is a test message.'))
        })
  })
hutianyu2006 commented 1 year ago

Uhh, I realized what I have missed. Sorry for a useless issue.

wemeetagain commented 1 year ago

@hutianyu2006 can you share what you missed? Will be helpful for people in the future with the same issue.

hutianyu2006 commented 1 year ago

@wemeetagain Currently I can't get my computer, so I can only recite it based on my memory lmao😂

The event listener should look like this:

libp2p.addEventListener('peer:connect', (evt) => {
            const peerId = evt.detail
            log(`Connected to ${peerId.toString()}`)
            libp2p.services.pubsub.connect(evt.detail)
            libp2p.services.pubsub.subscribe('test')
            libp2p.services.pubsub.publish('test', new TextEncoder().encode('This is a test message.'))
        })
  })

which means I simply changed the addPeer() function into a connect() function.

By the way, there is a tiny question: Is it possible to add the libp2p.services.pubsub.connect(peerId) function into the example code of usage section? Otherwise that will cause confusing errors to newbies.