2017-07-04 11:43:45 +01:00
|
|
|
'use strict'
|
|
|
|
/* eslint-disable no-console */
|
|
|
|
|
|
|
|
const PeerId = require('peer-id')
|
|
|
|
const PeerInfo = require('peer-info')
|
2017-07-05 12:12:51 +01:00
|
|
|
const Node = require('./libp2p-bundle')
|
2019-11-27 06:43:17 -05:00
|
|
|
const { stdinToStream, streamToConsole } = require('./stream')
|
2017-07-04 11:43:45 +01:00
|
|
|
|
2019-11-27 06:43:17 -05:00
|
|
|
async function run() {
|
|
|
|
const [idDialer, idListener] = await Promise.all([
|
|
|
|
PeerId.createFromJSON(require('./peer-id-dialer')),
|
|
|
|
PeerId.createFromJSON(require('./peer-id-listener'))
|
|
|
|
])
|
|
|
|
|
|
|
|
// Create a new libp2p node on localhost with a randomly chosen port
|
|
|
|
const peerDialer = new PeerInfo(idDialer)
|
2017-07-11 01:39:57 -05:00
|
|
|
peerDialer.multiaddrs.add('/ip4/0.0.0.0/tcp/0')
|
2018-06-28 10:06:25 +02:00
|
|
|
const nodeDialer = new Node({
|
|
|
|
peerInfo: peerDialer
|
|
|
|
})
|
2017-07-04 11:43:45 +01:00
|
|
|
|
2019-11-27 06:43:17 -05:00
|
|
|
// Create a PeerInfo with the listening peer's address
|
|
|
|
const peerListener = new PeerInfo(idListener)
|
2017-07-11 01:39:57 -05:00
|
|
|
peerListener.multiaddrs.add('/ip4/127.0.0.1/tcp/10333')
|
2017-07-04 11:43:45 +01:00
|
|
|
|
2019-11-27 06:43:17 -05:00
|
|
|
// Start the libp2p host
|
|
|
|
await nodeDialer.start()
|
2017-07-04 11:43:45 +01:00
|
|
|
|
2019-11-27 06:43:17 -05:00
|
|
|
// Output this node's address
|
|
|
|
console.log('Dialer ready, listening on:')
|
|
|
|
peerListener.multiaddrs.forEach((ma) => {
|
|
|
|
console.log(ma.toString() + '/p2p/' + idListener.toB58String())
|
|
|
|
})
|
2017-07-04 11:43:45 +01:00
|
|
|
|
2019-11-27 06:43:17 -05:00
|
|
|
// Dial to the remote peer (the "listener")
|
|
|
|
const { stream } = await nodeDialer.dialProtocol(peerListener, '/chat/1.0.0')
|
2017-07-04 11:43:45 +01:00
|
|
|
|
2019-11-27 06:43:17 -05:00
|
|
|
console.log('Dialer dialed to listener on protocol: /chat/1.0.0')
|
|
|
|
console.log('Type a message and see what happens')
|
|
|
|
|
|
|
|
// Send stdin to the stream
|
|
|
|
stdinToStream(stream)
|
|
|
|
// Read the stream and output to console
|
|
|
|
streamToConsole(stream)
|
|
|
|
}
|
|
|
|
|
|
|
|
run()
|