This repository was archived by the owner on Jul 7, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.js
More file actions
76 lines (66 loc) · 1.84 KB
/
client.js
File metadata and controls
76 lines (66 loc) · 1.84 KB
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
const NET = require('net');
const PROCESS = require('process');
const READLINE = require('readline');
const PORT = 2876;
PROCESS.stdin.setEncoding('utf8');
const NoIPError = 'An IP address must be entered.';
const InvalidIPError = 'Invalid IP address entered.';
const NoMessageContentError = 'A message must be entered.';
const RLInputClosedError = 'Readline Input was closed.';
const RLINPUT = READLINE.createInterface({
input: PROCESS.stdin,
output: PROCESS.stdout
});
function RLQUESTION(rl, question) {
return new Promise((resolve, reject) => {
function closeListener() {
reject(RLInputClosedError);
}
rl.once('close', closeListener);
rl.question(question, (answer) => {
rl.off('close', closeListener);
resolve(answer);
});
})
}
function UNTILEVENT(emitter, event) {
return new Promise((resolve, reject) => {
emitter.once(event, (...a) => resolve(...a))
});
}
;(async () => {
const host = await RLQUESTION(RLINPUT, 'IP to connect to: ');
if (host == null) {
RLINPUT.close();
throw NoIPError;
}
console.log('Received remote: ' + host);
const CLIENT = new NET.Socket();
CLIENT.connect(PORT, host, function() {
console.log('CONNECTING TO: ' + host + ':' + PORT + '...');
});
CLIENT.on('connect', function() {
console.log('CONNECTION ESTABLISHED AT: ' + host + ':' + PORT);
});
CLIENT.on('close', function() {
CLIENT.destroy();
RLINPUT.close();
console.log('Connection closed.');
});
await UNTILEVENT(CLIENT, 'ready');
try {
while(true) {
const data = await RLQUESTION(RLINPUT, 'Enter the message you want to send: ');
if (data == null) {
console.log('No message content provided -> no message sent');
} else {
CLIENT.write(data, 'utf-8');
}
}
} catch(e) {
console.log(e === RLInputClosedError ? '<close signal>' : '');
CLIENT.destroy();
if(e !== RLInputClosedError)
throw e;
}
})()