Skip to content

Instantly share code, notes, and snippets.

@tgoldenberg
Created April 10, 2018 02:44
Show Gist options
  • Save tgoldenberg/1757fd062fb0ffa69d8dea56c087ee15 to your computer and use it in GitHub Desktop.
Save tgoldenberg/1757fd062fb0ffa69d8dea56c087ee15 to your computer and use it in GitHub Desktop.
Basic networking
const net = require('net');
const network = require('network');
const uuid = require('uuid');
const SHA256 = require('js-sha256');
const port = parseInt(process.env.PORT);
function handleConnection(conn) {
console.log('> New client connection: ', conn.remoteAddress, conn.remotePort);
conn.setEncoding('utf8');
conn.on('data', data => {
console.log('> Received data: ', data);
})
}
function connectWithPeer() {
// get my IP address
network.get_public_ip((err, ip) => {
if (err)
throw err;
console.log('> Connected : ', ip, port);
// create server
const server = net.createServer();
server.on('connection', handleConnection);
server.listen(port, '0.0.0.0', () => {
console.log('> Listening on : ', server.address());
});
// if PORT == 8081 connect with peer
if (port === 8335) {
console.log('> Connecting to server...');
// write message
const client = new net.Socket();
client.connect(8334, '0.0.0.0', () => {
console.log('> Connected to peer.');
client.write(`VERSION 1 ${SHA256(uuid())}`);
});
client.on('data', data => {
console.log('> Received data: ', data);
});
}
})
}
connectWithPeer();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment