-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.js
63 lines (47 loc) · 1.39 KB
/
client.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
const { Socket } = require('net');
const readline = require('readline').createInterface({
input: process.stdin,
output: process.stdout,
});
const END = 'END';
const error = (err)=>{
console.log(err);
process.exit(1);
}
const connect = (host, port)=>{
console.log(`Connecting to ${host}:${port}`);
const socket = new Socket();
socket.connect({host: 'localhost', port: 8000});
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 exit.`);
});
readline.on('line', (message)=>{
socket.write(message)
if(message === END){
socket.end();
console.log('Disconnected');
}
});
});
socket.on('data', (message)=> console.log(message));
socket.on('close', ()=> process.exit(0));
socket.on('error', (err) => error(err.message));
}
const main = ()=>{
if(process.argv.length !== 4){
error(`Usage: node ${__filename} host port`);
}
let [, ,host, port] = process.argv;
if(port.isNaN){
error(`invalid port ${port}`);
}
port = Number(port);
connect(host, port);
}
if(module === require.main){
main();
}