forked from Klammer-b/simple-tcp-chat
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.js
87 lines (66 loc) · 1.9 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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
const net = require('net');
const readline = require('readline/promises');
const { ACTION_TYPES } = require('./constants');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
let clientId;
const socket = net.createConnection({ port: 3099, host: '127.0.0.1' });
const moveCursor = (x, y) =>
new Promise((resolve, reject) =>
process.stdout.moveCursor(x, y, () => resolve()),
);
const clearLine = (pos) =>
new Promise((resolve, reject) =>
process.stdout.clearLine(pos, () => resolve()),
);
const clearPreviousLine = async () => {
await moveCursor(0, -1);
await clearLine(0);
};
const ask = async () => {
const message = await rl.question('Enter your message: ');
await clearPreviousLine();
await socket.write(
JSON.stringify({
type: ACTION_TYPES.MESSAGE_SENT,
user: { id: clientId },
message,
}),
);
};
const onConnectionEstablished = (data) => {
clientId = data.user.id;
};
const onUserJoinedHandler = async (data) => {
console.log();
await clearPreviousLine();
console.log(`User with id ${data.user.id} is joined!`);
await ask();
};
const onUserLeftHandler = async (data) => {
console.log();
await clearPreviousLine();
console.log(`User with id ${data.user.id} is left`);
await ask();
};
const onMessageSentHandler = async (data) => {
console.log();
await clearPreviousLine();
console.log(`User ${data.user.id}: ${data.message}`);
await ask();
};
const actionTypesMapper = {
[ACTION_TYPES.CONNECTION_ESTABLISHED]: onConnectionEstablished,
[ACTION_TYPES.USER_JOINED]: onUserJoinedHandler,
[ACTION_TYPES.USER_LEFT]: onUserLeftHandler,
[ACTION_TYPES.MESSAGE_SENT]: onMessageSentHandler,
};
socket.on('connect', () => {
socket.on('data', async (data) => {
const payload = JSON.parse(data.toString('utf-8'));
const handler = actionTypesMapper[payload.type];
await handler(payload);
});
});