-
Notifications
You must be signed in to change notification settings - Fork 0
/
p2p.js
89 lines (75 loc) · 2.2 KB
/
p2p.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
const topology = require('fully-connected-topology')
const {
stdin,
exit,
argv
} = process
const {
log
} = console
const {
me,
peers
} = extractPeersAndMyPort()
const sockets = {}
log('---------------------')
log('Welcome to p2p chat!')
log('me - ', me)
log('peers - ', peers)
log('connecting to peers...')
const myIp = toLocalIp(me)
const peerIps = getPeerIps(peers)
//connect to peers
topology(myIp, peerIps).on('connection', (socket, peerIp) => {
const peerPort = extractPortFromIp(peerIp)
log('connected to peer - ', peerPort)
sockets[peerPort] = socket
stdin.on('data', data => { //on user input
const message = data.toString().trim()
if (message === 'exit') { //on exit
log('Bye bye')
exit(0)
}
const receiverPeer = extractReceiverPeer(message)
if (sockets[receiverPeer]) { //message to specific peer
if (peerPort === receiverPeer) { //write only once
sockets[receiverPeer].write(formatMessage(extractMessageToSpecificPeer(message)))
}
} else { //broadcast message to everyone
socket.write(formatMessage(message))
}
})
//print data when received
socket.on('data', data => log(data.toString('utf8')))
})
//extract ports from process arguments, {me: first_port, peers: rest... }
function extractPeersAndMyPort() {
return {
me: argv[2],
peers: argv.slice(3, argv.length)
}
}
//'4000' -> '127.0.0.1:4000'
function toLocalIp(port) {
return `127.0.0.1:${port}`
}
//['4000', '4001'] -> ['127.0.0.1:4000', '127.0.0.1:4001']
function getPeerIps(peers) {
return peers.map(peer => toLocalIp(peer))
}
//'hello' -> 'myPort:hello'
function formatMessage(message) {
return `${me}>${message}`
}
//'127.0.0.1:4000' -> '4000'
function extractPortFromIp(peer) {
return peer.toString().slice(peer.length - 4, peer.length);
}
//'4000>hello' -> '4000'
function extractReceiverPeer(message) {
return message.slice(0, 4);
}
//'4000>hello' -> 'hello'
function extractMessageToSpecificPeer(message) {
return message.slice(5, message.length);
}