-
Notifications
You must be signed in to change notification settings - Fork 0
/
chat.js
80 lines (64 loc) · 1.86 KB
/
chat.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
import chalk from 'chalk';
import dgram from 'dgram';
import events from 'events';
export default class Chat {
constructor(options) {
const emitter = new events.EventEmitter();
const socket = dgram.createSocket({
type: 'udp4',
});
socket.on('listening', () => {
const { port } = this.socket.address();
console.log(`Listening UDP socket for p2p chat @ port ${port}`);
emitter.emit('ready', port);
});
socket.on('error', (error) => {
console.error(`Something went wrong: ${error.message}`);
});
socket.on('message', (data, info) => {
// Find identifier of this peer
const peer = this.peers.find((peer) => {
return peer.address === info.address && peer.port === info.port;
});
// Received data from unknown peer, let's ignore it
if (!peer) {
return;
}
// Show message
const message = String.fromCharCode.apply(String, data);
console.log(`${chalk.green.bold(peer.id)}: ${chalk.green(message)}`);
});
// Bind a UDP socket listening to a random port (given by the OS)
socket.bind();
this.socket = socket;
this.emitter = emitter;
this.options = options;
this.peers = [];
}
send(message) {
const data = Buffer.from(message);
// Send a chat message to all known peers, one by one
this.peers.forEach(({ address, port }) => {
this.socket.send(data, 0, data.length, port, address);
});
}
addPeer({ address, port, id }) {
// Check if peer is already registered
const exists = this.peers.find((peer) => {
return peer.id === id;
});
if (exists) {
return;
}
this.peers.push({
address,
port: parseInt(port),
id,
});
console.log(
`${chalk.green('★')} Found new peer ${chalk.green.bold(
id,
)} @ ${address}:${port}`,
);
}
}