-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathclient.js
More file actions
65 lines (51 loc) · 1.29 KB
/
client.js
File metadata and controls
65 lines (51 loc) · 1.29 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
const { Socket } = require("net");
const readline = require("readline").createInterface({
input: process.stdin,
output: process.stdout,
});
const END = "END";
const error = (message) => {
console.error(message);
process.exit(1);
};
const connect = (host, port) => {
console.log(`Connecting to ${host}:${port}`);
const socket = new Socket();
socket.connect({ host, port });
socket.setEncoding("utf-8");
socket.on("connect", () => {
console.log("Connected");
readline.question("Choose your username: ", (username) => {
socket.write(username);
console.log(`Type any message to send it, type ${END} to finish`);
});
readline.on("line", (message) => {
socket.write(message);
if (message === END) {
socket.end();
}
});
socket.on("data", (data) => {
console.log(data);
});
});
socket.on("error", (err) => error(err.message));
socket.on("close", () => {
console.log("Disconnected");
process.exit(0);
});
};
const main = () => {
if (process.argv.length !== 4) {
error(`Usage: node ${__filename} host port`);
}
let [, , host, port] = process.argv;
if (isNaN(port)) {
error(`Invalid port ${port}`);
}
port = Number(port);
connect(host, port);
};
if (module === require.main) {
main();
}