forked from illuspas/Node-Media-Server
-
Notifications
You must be signed in to change notification settings - Fork 0
/
node_media_cluster.js
63 lines (50 loc) · 1.32 KB
/
node_media_cluster.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
//
// Created by Mingliang Chen on 18/6/20.
// illuspas[a]gmail.com
// Copyright (c) 2018 Nodemedia. All rights reserved.
//
const NodeMediaServer = require('./node_media_server');
const cluster = require('cluster');
const context = require('./node_core_ctx');
const Logger = require('./node_core_logger');
class NodeMediaCluster {
constructor(config) {
this.config = config;
}
run() {
if (cluster.isMaster) {
Logger.log(`Master ${process.pid} is running`);
const messageHandler = (msg) => {
for (let id in cluster.workers) {
cluster.workers[id].send(msg);
}
}
const newWorker = () => {
let worker = cluster.fork();
worker.on('message', messageHandler);
}
for (let i = 0; i < this.config.cluster.num; i++) {
newWorker();
}
cluster.on('exit', (worker, code, signal) => {
Logger.log(`worker ${worker.process.pid} died`);
newWorker();
});
} else {
this.nms = new NodeMediaServer(this.config);
this.nms.run();
Logger.log(`worker ${process.pid} started`);
}
}
on(eventName, listener) {
if (cluster.isWorker) {
context.nodeEvent.on(eventName, listener);
}
}
stop() {
if (cluster.isWorker) {
this.nms.stop();
}
}
}
module.exports = NodeMediaCluster