node_ipc_server.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. //
  2. // Created by Mingliang Chen on 18/6/19.
  3. // illuspas[a]gmail.com
  4. // Copyright (c) 2018 Nodemedia. All rights reserved.
  5. //
  6. const NodeRtmpSession = require('./node_rtmp_session');
  7. const NodeIpcSession = require('./node_ipc_session');
  8. const context = require('./node_core_ctx');
  9. const Logger = require('./node_core_logger');
  10. const Net = require('net');
  11. class NodeIpcServer {
  12. constructor(config) {
  13. this.config = config;
  14. this.sessions = new Map();
  15. this.ipcPort = 0;
  16. this.ipcServer = Net.createServer((socket) => {
  17. let session = new NodeRtmpSession(config, socket);
  18. session.isIPC = true;
  19. session.run();
  20. })
  21. }
  22. run() {
  23. this.ipcServer.listen({ port: 0, host: '127.0.0.1', exclusive: true }, () => {
  24. this.ipcPort = this.ipcServer.address().port;
  25. Logger.log(`Node Media IPC Server started at`, this.ipcPort);
  26. });
  27. context.nodeEvent.on('postPublish', this.onPostPublish.bind(this));
  28. context.nodeEvent.on('donePublish', this.onDonePublish.bind(this));
  29. process.on('message', (msg) => {
  30. if (this.ipcPort === msg.port) {
  31. Logger.debug('[rtmp ipc] Current process, ignore');
  32. return;
  33. }
  34. Logger.debug(`[rtmp ipc] receive message from pid=${msg.pid} cmd=${msg.cmd} port=${msg.port} streamPath=${msg.streamPath}`);
  35. if (msg.cmd === 'postPublish') {
  36. let ipcSession = new NodeIpcSession(msg.streamPath, msg.port, this.ipcPort);
  37. this.sessions.set(msg.streamPath, ipcSession);
  38. ipcSession.run();
  39. } else if (msg.cmd === 'donePublish') {
  40. let ipcSession = this.sessions.get(msg.streamPath);
  41. ipcSession.stop();
  42. this.sessions.delete(msg.streamPath);
  43. }
  44. });
  45. }
  46. stop() {
  47. this.ipcServer.close();
  48. }
  49. onPostPublish(id, streamPath, args) {
  50. process.send({ cmd: 'postPublish', pid: process.pid, port: this.ipcPort, streamPath });
  51. }
  52. onDonePublish(id, streamPath, args) {
  53. process.send({ cmd: 'donePublish', pid: process.pid, port: this.ipcPort, streamPath });
  54. }
  55. }
  56. module.exports = NodeIpcServer