go-libp2p-webrtc-direct/examples/standalone/index.js

56 lines
1.4 KiB
JavaScript
Raw Normal View History

const flags = require('flags')
const WebRTCDirect = require('libp2p-webrtc-direct')
const multiaddr = require('multiaddr')
const mplex = require('libp2p-mplex')
const pull = require('pull-stream')
const listenFlag = 'listen'
flags.defineBoolean(listenFlag, false, 'Listen for incoming connections.')
flags.parse()
const listening = flags.get(listenFlag)
2019-02-14 16:37:30 +00:00
const maddr = multiaddr('/ip4/127.0.0.1/tcp/9090/http/p2p-webrtc-direct')
const direct = new WebRTCDirect()
if (listening) {
const listener = direct.createListener({ config: {} }, (conn) => {
console.log('[listener] Got connection')
const muxer = mplex.listener(conn)
muxer.on('stream', (stream) => {
console.log('[listener] Got stream')
pull(
stream,
pull.drain((data) => {
console.log('[listener] Received:')
console.log(data.toString())
})
)
})
})
2019-02-14 16:37:30 +00:00
listener.listen(maddr, () => {
console.log('[listener] Listening')
})
} else {
2019-02-14 16:37:30 +00:00
direct.dial(maddr, { config: {} }, (err, conn) => {
if (err) {
console.log(`[dialer] Failed to open connection: ${err}`)
}
console.log('[dialer] Opened connection')
const muxer = mplex.dialer(conn)
const stream = muxer.newStream((err) => {
console.log('[dialer] Opened stream')
if (err) throw err
})
pull(
pull.values(['hey, how is it going. I am the dialer']),
stream
)
})
}