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
57 lines (47 loc) · 1.81 KB
/
Copy pathmediator.js
File metadata and controls
57 lines (47 loc) · 1.81 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
const WebSocketServer = require('websocket').server;
const http = require('http');
const { SOCKET_MSG_MAX_SIZE } = require('./config');
const logger = require('./utils/logger');
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();
httpServer.listen(port, () => logger.info(`+ started: mediator server, 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,
maxReceivedFrameSize: SOCKET_MSG_MAX_SIZE,
maxReceivedMessageSize: SOCKET_MSG_MAX_SIZE
});
webSocketServer.on('request', request => {
const connection = request.accept(null, request.origin);
const isClient = request.origin && request.origin.includes(`:${clientPort}`);
if (isClient) {
clientInstance = connection;
logger.info('> browser 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
};