-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
87 lines (68 loc) · 1.98 KB
/
server.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
'use strict';
const net = require('net');
const tasks = [];
const customers = [];
const workers = [];
let id = 0;
const checkTasks = () => {
if (tasks.length) {
const worker = workers.pop();
const task = tasks.shift();
worker.write(JSON.stringify(task));
}
};
const sendTask = (task, customerId) => {
const data = { task, customerId };
if (workers.length) {
const worker = workers.pop();
worker.write(JSON.stringify(data));
} else {
tasks.push(data);
console.log(
`--- Please wait, customer ${customerId}, all workers are busy ---`
);
}
};
const sendResult = data => {
const { result, customerId } = data;
const customer = customers.find(x => x.id === customerId);
customer.write(JSON.stringify(result));
};
const server = net.createServer((socket) => {
console.log('**New connection to the server**');
socket.id = id++;
socket.on('data', (data) => {
data = JSON.parse(data);
if (data === 'worker') {
console.log('(it was worker)');
workers.push(socket);
checkTasks();
} else if (data.result) {
console.log('receive Result for customer', data.customerId);
sendResult(data);
workers.push(socket);
checkTasks();
} else {
console.log('receive Task from customer', socket.id);
customers.push(socket);
const customerId = socket.id;
sendTask(data, customerId);
}
});
socket.on('close', () => {
const indexCustomer = customers.indexOf(socket);
if (indexCustomer !== -1) {
customers.splice(indexCustomer, 1);
} else {
const indexWorker = workers.indexOf(socket);
workers.splice(indexWorker, 1);
}
console.log(
`Socket closed, left connections: ${workers.length + customers.length}`,
`\nworkers: ${workers.length}, customers: ${customers.length}`
);
});
});
server.listen(2020, () => {
console.log('Listening start...');
});