IPFS- How to send message from a peer to another?

2.9k views Asked by At

I am looking for a solution to send a message from an IPFS peer to another

in the github doc I found this code that connect a peer to another one :

ipfs.swarm.connect(addr, function (err) {
  if (err) {
    throw err
  }
  // if no err is present, connection is now open
})

but after connection there is nothing to do according to documentation.

There a solution named ipfs-pubsub-room that deal with messaging between peers, but there is no CDN for browser.

2

There are 2 answers

3
Steven On

ipfs.swarm.connect will simply connect both nodes so that they can exchange files.

ipfs-pubsub-room should work just fine from a browser but yes, you'll need to package it yourself.

However, you can also use libp2p, IPFS's networking library, directly via the ipfs.libp2p property if you just need to send a message directly from one peer to another.

To listen for inbound messages, you can register a "protocol handler" on one of your nodes:

const pull = require('pull-stream')
ipfs.libp2p.handle('/my/protocol/name/1.0.0', (protocolName, connection) => {
  pull(connection, pull.collect((err, data) => {
    console.log("received:", data.toString())
  }))
})

(Where ipfs is an initialized IPFS node object, not the IPFS import.)

To send a message, you'll have to "dial" the peer/protocol:

const pull = require('pull-stream')
ipfs.libp2p.dialProtocol(addr, '/my/protocol/name/1.0.0', (err, connection) => {
  pull(pull.values(["my message"]), connection)
})

You can find a complete example in the js-ipfs documentation.

0
momack2 On

IPFS is a file system, so once you have two peers connected they can add and get files to share content between those nodes. If your "message" can be encoded as a file that node A adds (https://docs.ipfs.io/reference/api/cli/#ipfs-add) and node B gets (https://docs.ipfs.io/reference/api/cli/#ipfs-get), then they can exchange messages that way.

Check out https://docs.ipfs.io/introduction/usage/ for general usage instructions.