Skip to content

Instantly share code, notes, and snippets.

@theatom06
Last active March 28, 2023 14:30
Show Gist options
  • Save theatom06/d458a84579c5223102ae46667ae8f25d to your computer and use it in GitHub Desktop.
Save theatom06/d458a84579c5223102ae46667ae8f25d to your computer and use it in GitHub Desktop.
A simple p2p connection in node.js based on node:net module
//Import the net module
const net = require('net');
//Create a server which is our connecting point
const server = net.createServer((socket) => {
//got some data? well reply!
socket.on('data', (data) => {
console.log(`Received data: ${data}`);
socket.write('Recevied data!');
});
});
//start the server!!
server.listen(3000, () => {
console.log('Server listening on port 3000');
});
//wait cause we cant be flash
setTimeout(() => {
//connect
const client = net.connect({
port: 3000,
host: '192.168.1.37'
}, () => {
console.log("Connected to peer")
});
client.on('data', (data) => {
console.log(`Received data: ${data}`);
});
client.write('Hello, peer!!');
}, 10000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment