forked from CodecrumbsIO/codecrumbs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmediator.js
More file actions
55 lines (46 loc) · 1.83 KB
/
Copy pathmediator.js
File metadata and controls
55 lines (46 loc) · 1.83 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
const WebSocketServer = require('websocket').server;
const http = require('http');
const { SOCKET_MESSAGE_TYPE } = require('../shared/constants');
// instances should run on many ports but then send data to mediator and mediator to client
const run = ({ port, clientPort }) => {
const httpServer = http.createServer((request, response) => {
// TODO: refactor this to work with sockets instead
response.writeHead(500, { 'Content-Type': 'text/html' });
response.write('STOP USE HTTP! Will be moved to sockets!');
response.end();
});
httpServer.listen(port, () => console.log(`Mediator server is listening: ${port}.`));
let clientInstance = null;
const sendToClient = event => clientInstance && clientInstance.sendUTF(event);
const sourceWatcherInstances = [];
const sendToSourceWatchers = event => sourceWatcherInstances.forEach(l => l.sendUTF(event));
const webSocketServer = new WebSocketServer({ httpServer });
webSocketServer.on('request', request => {
const connection = request.accept(null, request.origin);
const isClient = request.origin && request.origin.includes(`:${clientPort}`);
if (isClient) {
clientInstance = connection;
console.log('Client connected.');
sendToSourceWatchers(
JSON.stringify({
type: SOCKET_MESSAGE_TYPE.CLIENT_CONNECTED
})
);
} else {
sourceWatcherInstances.push(connection);
}
connection.on('message', ({ utf8Data }) => {
const sendAnswer = isClient ? sendToSourceWatchers : sendToClient;
sendAnswer(utf8Data);
});
connection.on('close', () => {
const sourceWatcherIndex = sourceWatcherInstances.findIndex(watcher => !watcher.connected);
if (sourceWatcherIndex !== -1) {
sourceWatcherInstances.splice(sourceWatcherIndex, 1);
}
});
});
};
module.exports = {
run
};