Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
var hypercore = require("hypercore")
var hyperswarm = require("hyperswarm")
var crypto = require("crypto")
var pump = require("pump")
var ram = require("random-access-memory")
function initiate (topic, opts) {
var swarm = hyperswarm({ announceLocalAddress: true })
var topicBuffer = crypto.createHash('sha256')
.update(topic)
.digest()
swarm.join(topicBuffer, opts)
return swarm
}
let tunnelHandler = {
encoding: "utf-8",
onmessage (msg, peer) {
console.log("tunnel->", msg)
},
onerror (err) {
console.error("tunnel handler had an error", err)
}
}
let feedname = process.argv.slice(2)[0]
if (!feedname) {
console.error("Usage: node script.js 'null'|<feedkey>")
process.exit()
}
let feedopts = { valueEncoding: "utf-8" }
let feed = feedname === "null" ?
hypercore(ram, feedopts) :
hypercore(ram, feedname, feedopts)
let ext = feed.registerExtension("tunnel", tunnelHandler)
console.dir(ext)
feed.on("ready", () => {
console.log("feed ready")
console.log("key:", feed.key.toString("hex"))
setInterval(() => {
let msg = "hello i am "
msg += feedname === "null" ? 'the originator' : 'the initiator'
ext.broadcast(msg)
}, 500)
let swarm = initiate("charon", { lookup: true, announce: true })
swarm.on("connection", (socket, details) => {
console.log("swarm details.client: ", details.client)
var r = feed.replicate(details.client)
pump(socket, r, socket, function (err) {
if (err) console.error("error in pump", err)
})
})
swarm.on("peer", (peer) => {
console.log("received peer", peer.host)
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment