Last active
March 1, 2018 00:04
-
-
Save YanLobat/a9d3886fbe8dd77ea3f3343bf1b38d1d to your computer and use it in GitHub Desktop.
This file contains hidden or 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 net = require('net'); | |
let port = 3000; | |
let isRoot = false; | |
const connectionList = new Map(); | |
const expireDelta = 5*60*1000; | |
const server = net.createServer(socket => { | |
socket.on('error', err => { | |
console.log(err); | |
}); | |
socket.on('data', function (data) { | |
const str = data.toString(); | |
connectionList.set(JSON.parse(str), Date.now() + expireDelta); | |
socket.write(connectionList.map(p => p.port).join(',')); | |
}); | |
}); | |
server.listen(port); | |
setInterval(checkExpire, 500) | |
server.on('error', err => { | |
if (err.code === 'EADDRINUSE') { | |
server.close(); | |
port += 1; | |
server.listen(port); | |
} | |
}); | |
server.on('listening', () => { | |
if (port === 3000) { | |
isRoot = true; | |
return; | |
} | |
connectRoot(); | |
connectPeers(); | |
client.on('data', function(data) { | |
console.log('Connection list: ' + data); | |
}); | |
}); | |
function checkExpire() { | |
const now = Date.now(); | |
for (let [ port, exipireTime ] of connectionList.entries()) { | |
if (exipireTime < now) { | |
connectionList.delete(port); | |
} | |
} | |
} | |
function connectRoot() { | |
const client = new net.Socket(); | |
client.connect(3000, '127.0.0.1', function() { | |
console.log('Connected'); | |
client.write(JSON.stringify({ port })); | |
}); | |
} | |
function connectPeers() { | |
const peerPorts = getNeighborsPorts(port); | |
peerPorts.forEach(port => { | |
const client = new net.Socket(); | |
client.connect(port, '127.0.0.1', () => { | |
console.log('Connected to peer '+port); | |
}); | |
}); | |
} | |
function getNeighborsPorts(port) { | |
let guess = port + 1; | |
const ports = []; | |
while (ports.length !== 3) { | |
if (connectionList.has(guess)) { | |
count++; | |
ports.push(guess); | |
} else { | |
if (guess > port) { | |
guess = port -1; | |
} else { | |
guess--; | |
} | |
} | |
} | |
return ports; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment