|
1 | 1 | /* eslint-disable no-console */
|
2 | 2 |
|
3 |
| -import { createFromJSON } from '@libp2p/peer-id-factory' |
4 |
| -import { multiaddr } from '@multiformats/multiaddr' |
5 | 3 | import { createLibp2p } from './libp2p.js'
|
6 |
| -import peerIdDialerJson from './peer-id-dialer.js' |
7 |
| -import peerIdListenerJson from './peer-id-listener.js' |
8 | 4 | import { stdinToStream, streamToConsole } from './stream.js'
|
9 | 5 |
|
10 | 6 | async function run () {
|
11 |
| - const [idDialer, idListener] = await Promise.all([ |
12 |
| - createFromJSON(peerIdDialerJson), |
13 |
| - createFromJSON(peerIdListenerJson) |
14 |
| - ]) |
15 |
| - |
16 | 7 | // Create a new libp2p node on localhost with a randomly chosen port
|
17 |
| - const nodeDialer = await createLibp2p({ |
18 |
| - peerId: idDialer, |
| 8 | + const dialer = await createLibp2p({ |
19 | 9 | addresses: {
|
20 | 10 | listen: ['/ip4/0.0.0.0/tcp/0']
|
21 | 11 | }
|
22 | 12 | })
|
23 | 13 |
|
24 | 14 | // Output this node's address
|
25 | 15 | console.log('Dialer ready, listening on:')
|
26 |
| - nodeDialer.getMultiaddrs().forEach((ma) => { |
| 16 | + dialer.getMultiaddrs().forEach((ma) => { |
27 | 17 | console.log(ma.toString())
|
28 | 18 | })
|
29 | 19 |
|
30 |
| - // Dial to the remote peer (the "listener") |
31 |
| - const listenerMa = multiaddr(`/ip4/127.0.0.1/tcp/10333/p2p/${idListener.toString()}`) |
32 |
| - const stream = await nodeDialer.dialProtocol(listenerMa, '/chat/1.0.0') |
| 20 | + dialer.addEventListener('peer:discovery', (evt) => { |
| 21 | + console.info('peer:discovery', evt.detail) |
33 | 22 |
|
34 |
| - console.log('Dialer dialed to listener on protocol: /chat/1.0.0') |
35 |
| - console.log('Type a message and see what happens') |
| 23 | + // Dial to the remote peer (the "listener") |
| 24 | + dialer.dialProtocol(evt.detail.multiaddrs, '/chat/1.0.0') |
| 25 | + .then(stream => { |
| 26 | + console.log('Dialer dialed to listener on protocol: /chat/1.0.0') |
| 27 | + console.log('Type a message and see what happens') |
36 | 28 |
|
37 |
| - // Send stdin to the stream |
38 |
| - stdinToStream(stream) |
39 |
| - // Read the stream and output to console |
40 |
| - streamToConsole(stream) |
| 29 | + // Send stdin to the stream |
| 30 | + stdinToStream(stream) |
| 31 | + // Read the stream and output to console |
| 32 | + streamToConsole(stream) |
| 33 | + }) |
| 34 | + }) |
41 | 35 | }
|
42 | 36 |
|
43 | 37 | run()
|
0 commit comments