forked from rolling-scopes-school/websockets-ui
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
62 lines (45 loc) · 1.56 KB
/
index.ts
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
import { httpServer } from './src/http_server/index';
import { createWebSocketStream, WebSocketServer } from 'ws';
import { runCommand } from './src/modules/runCommand';
const HTTP_PORT = 3000;
console.log(`Start static http server on the ${HTTP_PORT} port`);
httpServer.listen(HTTP_PORT);
const WS_PORT = 8080;
const webSocketServer = new WebSocketServer({ port: WS_PORT });
console.log(`Start web socket server on the ${WS_PORT} port`);
webSocketServer.on('connection', (ws) => {
console.log('A client has just connected');
const duplex = createWebSocketStream(ws, { encoding: 'utf8', decodeStrings: false });
duplex.on('data', async (data) => {
try {
const input = data.toString();
const output = await runCommand(input);
console.log('<-', input);
const result = `${input} ${output ? output : ''}`;
if (typeof result === 'string') {
console.log('Operation successful');
duplex.write(result, (error) => {
if (error instanceof Error) {
console.log(`Operation failed, error: ${error}`);
}
});
}
} catch (error) {
console.log(`Operation failed, error: ${error}`);
}
});
ws.on('error', (error) => {
console.log(`Operation failed, error: ${error}`);
});
ws.on('close', () => {
console.log('Websocket has been closed');
});
});
webSocketServer.on('close', () => {
console.log('Web socket connection is closed');
});
process.on('SIGINT', () => {
console.log('Web socket server will be closed');
webSocketServer.close();
process.exit();
});