toy-peers
v0.3.1
Published
Simple network for Peer-To-Peer simulations
Downloads
8
Maintainers
Readme
toy-peers
Simple network for Peer-To-Peer simulations which provides all mechanisms to build a low-level peer-to-peer network.
toy-peers
relies on websockets to connect peers and exchange messages. Handshakes and offers are performed using Json Web Tokens.
Installation
npm install toy-peers --save
Getting started
Let's create a simple network with two peers connected to each other.
const Peer = require('toy-peers').Peer;
// peerA will run on port 80801, and peerB on port 8081
const peerA = new Peer(8080);
const peerB = new Peer(8081);
// launch peers
peerA.init();
peerB.init();
// listen for messages received from other peers
peerA.on('data', (id, message) => {
console.log('peerA: received message "' + message + '" from peer#' + id);
});
peerB.on('data', (id, message) => {
console.log('peerB: received message "' + message + '" from peer#' + id);
peerB.send(id, 'hello world to you too!');
});
// connect peerA and peerB and then send a message
peerA.connect(peerB.address)
.then(() => peerB.connect(peerA.address))
.then(() => {
// you can send data of any valid JS type (integer, string, Object, etc)
peerA.send(peerB.id, 'hello world!');
})
.catch(err => console.err('failed to connect: ' + err));
Documentation
Generate JSDoc documentation in doc/
directory with the following command
npm run doc
Testing
# run tests with Mocha + Chai
npm test
# compute code coverage with istanbul
npm run coverage