Send message to already connected peer (context: IPFS)

Is it possible to just directly send and receive messages with IPFS peers that are already in your swarm list?

If not, I take it the best way to do this is just opening another connection via ipfs.libp2p.dialProtocol and ipfs.libp2p.handle and copying the chat example? Does that even open a duplicate connection or will it use the existing one?

This is all in JavaScript from the browser for now, so the multiaddrs in question are of the form /p2p-circuit/ipfs/Qm...

There are a couple options you could use for doing this, depending on what you’re trying to achieve. Leveraging pubsub would be a good option if you want to broadcast messages to your network.

If pubsub doesn’t work for what you’re trying to do, then you can use ipfs.libp2p.dialProtocol as you’ve indicated. It will use the existing connection if there is one and just create a new stream. ipfs.swarm.peers will give you a list of your connected peers, so you could iterate over those for your dial.

1 Like

Perfect, thank you.

That answers my questions, but just for context:
I’m building an offline-first social network, and this question was in pursuit of an IPNS overlay so I can just have friends connect to each other directly to disseminate records, bypassing the slow DHT and somewhat limited IPNS pubsub. I’m avoiding pubsub more generally to make metadata about who’s talking to whom harder to snoop on. Also, I’ve found that the congestion gets really bad on pubsub even if you’re in a small room whenever unrelated rooms are active, so that’s another reason to handle connections directly.