feat(p2p): peers exchange

This commit is contained in:
Alexey Kasyanchuk
2018-03-03 05:49:52 +03:00
parent e8bef06697
commit c2b030dddc

View File

@ -34,7 +34,8 @@ class p2p {
return return
callback({ callback({
protocol: 'rats' protocol: 'rats',
peers: this.peersList().slice(0, 4).map(peer => ({address: peer.address, port: peer.port}))
}) })
// try to connect back // try to connect back
@ -45,6 +46,12 @@ class p2p {
port: data.port ? data.port : socket.remotePort port: data.port ? data.port : socket.remotePort
}) })
} }
// add some other peers
if(data.peers && data.peers.length > 0)
{
data.peers.forEach(peer => this.add(peer))
}
}) })
// ignore local addresses // ignore local addresses
@ -128,7 +135,8 @@ class p2p {
const protocolTimeout = setTimeout(() => rawSocket.destroy(), 7000) const protocolTimeout = setTimeout(() => rawSocket.destroy(), 7000)
emit('protocol', { emit('protocol', {
protocol: 'rats', protocol: 'rats',
port: config.spiderPort port: config.spiderPort,
peers: this.peersList().slice(0, 4).map(peer => ({address: peer.address, port: peer.port}))
}, (data) => { }, (data) => {
if(!data || data.protocol != 'rats') if(!data || data.protocol != 'rats')
return return
@ -140,6 +148,12 @@ class p2p {
this.size++; this.size++;
this.send('peer', this.size) this.send('peer', this.size)
console.log('new peer', address) console.log('new peer', address)
// add some other peers
if(data.peers && data.peers.length > 0)
{
data.peers.forEach(peer => this.add(peer))
}
}) })
}); });
@ -171,6 +185,11 @@ class p2p {
peer.emit(type, data, callback) peer.emit(type, data, callback)
} }
} }
peersList()
{
return this.peers.filter(peer => !!peer.emit)
}
} }
module.exports = p2p module.exports = p2p