Last active
October 6, 2020 08:16
-
-
Save vasco-santos/661537112663c31808f5503d813002f5 to your computer and use it in GitHub Desktop.
libp2p protocol
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const pipe = require('it-pipe') | |
// The codec of our protocol | |
const PROTOCOL = '/libp2p/kickoff-app/1.0.0' | |
/** | |
* A simple handler to print incoming messages to the console | |
* @param {Object} params | |
* @param {Connection} params.connection The connection the stream belongs to | |
* @param {Stream} params.stream stream to the peer | |
*/ | |
async function handler ({ connection, stream }) { | |
try { | |
await pipe( | |
stream, | |
async function (source) { | |
for await (const message of source) { | |
console.info(`${connection.remotePeer.toB58String().slice(0, 8)}: ${message}`) | |
} | |
} | |
) | |
// Replies are done on new streams, so let's close this stream so we don't leak it | |
await pipe([], stream) | |
} catch (err) { | |
console.error(err) | |
} | |
} | |
/** | |
* Writes a given `message` over the given `stream`. | |
* @param {String} message The message to send over `stream` | |
* @param {Stream} stream A stream over the muxed Connection to our peer | |
*/ | |
async function send (message, stream) { | |
try { | |
await pipe( | |
[message], | |
stream, | |
async function (source) { | |
for await (const message of source) { | |
console.info(`Me: ${message}`) | |
} | |
} | |
) | |
} catch (err) { | |
console.error(err) | |
} | |
} | |
module.exports = { | |
PROTOCOL, | |
handler, | |
send | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment