Skip to content

Instantly share code, notes, and snippets.

@gitawego
Created July 1, 2019 22:21
Show Gist options
  • Save gitawego/3f66b1d414c007080ef46ac2d7246d3d to your computer and use it in GitHub Desktop.
Save gitawego/3f66b1d414c007080ef46ac2d7246d3d to your computer and use it in GitHub Desktop.
swarm discovery
var swarm = require('discovery-swarm');
const crypto = require('crypto');
const net = require('net');
const topic = crypto.createHash('sha256')
.update('my key')
.digest();
console.log('args',process.argv);
const port = process.argv[2] || 10001;
var sw = swarm({
dns:{
server:['192.168.31.1']
}
})
const sockets = [];
const metadata = new WeakMap();
sw.listen(port);
sw.join(topic) // can be any id/name/hash
sw.on('connection', function (peerSocket,info) {
console.log('peer info',info);
if(!info.channel || info.channel !== topic){
return;
}
sockets.push(peerSocket);
peerSocket.on('data', function (data) {
console.log('on data', data.toString());
try{
metadata.set(peerSocket,JSON.parse(data.toString()));
}catch(err){
//
}
});
peerSocket.on('close', function () {
sockets.splice(sockets.indexOf(peerSocket),1);
console.log('Connection closed',sockets.length);
});
peerSocket.write(JSON.stringify({
namespace:'test '+port
}));
console.log('total sockets',sockets.length);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment