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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With