-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.js
More file actions
91 lines (74 loc) · 2.1 KB
/
client.js
File metadata and controls
91 lines (74 loc) · 2.1 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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
'use strict';
const tls = require('tls');
const rl = require('./client/rl');
const fs = require('fs');
const MessageQueue = require('./client/queue');
const { createMsg } = MessageQueue;
const { parseAddress, randomColorer } = require('./lib');
const options = {
ca: [ fs.readFileSync('./cert/server-cert.pem') ]
};
const socket = tls.connect(8000, options);
const queue = new MessageQueue(socket);
const saveCache = () => {
for (const address in queue.waiting) {
const cache = queue.waiting[ address ];
if (!cache) continue;
for (const msg of cache) socket.write(JSON.stringify(msg));
}
};
const operations = {
'/dialogue': async data => {
const address = parseAddress(data);
if (address) await queue.startDialogue(address);
},
'/leave': () => queue.leaveDialogue(),
'/exit': () => {
saveCache();
rl.close();
process.exit(0);
},
};
const executeCommand = async data => {
const command = data.substring(0, data.indexOf(' ')) || data;
const operation = operations[ command ];
if (operation) return await operation(data);
};
const processLine = async (line, login) => {
const username = randomColorer(login);
if (line.startsWith('/')) return await executeCommand(line);
const text = username + ' ' + line;
const message = createMsg(login, queue.colocutor, text);
return socket.write(message);
};
const onConnect = async () => {
const login = await rl.getLogin();
const password = await rl.getPassword();
socket.write(JSON.stringify({ type: 'login', login, password }));
queue.initialize(login);
rl.on('line', async line => processLine(line, login));
};
const onData = data => queue.add(data.toString());
const onError = err => {
console.log('Socket error: ', err);
rl.close();
socket.end();
};
const onEnd = () => {
console.log('Connection ended');
rl.close();
};
const events = {
'connect': onConnect,
'data': onData,
'error': onError,
'end': onEnd,
};
const addListeners = () => {
for (const event in events) {
const listener = events[ event ];
socket.on(event, listener);
}
};
addListeners();
rl.on('SIGINT', operations[ '/exit' ]);