mirror of
https://github.com/hensm/fx_cast.git
synced 2026-06-11 18:19:58 +00:00
App refactor (#140)
* Add additional types * Split components from single index module into smaller modules * Misc smaller changes
This commit is contained in:
61
app/src/daemon.ts
Normal file
61
app/src/daemon.ts
Normal file
@@ -0,0 +1,61 @@
|
||||
"use strict";
|
||||
|
||||
import { spawn } from "child_process";
|
||||
import { Readable } from "stream";
|
||||
|
||||
import minimist from "minimist";
|
||||
import WebSocket from "ws";
|
||||
|
||||
import { DecodeTransform
|
||||
, EncodeTransform } from "./transforms";
|
||||
|
||||
|
||||
export function init (port: number) {
|
||||
process.stdout.write("Starting WebSocket server... ");
|
||||
|
||||
const wss = new WebSocket.Server({ port }, () => {
|
||||
console.log("Done!");
|
||||
});
|
||||
|
||||
wss.on("error", (err) => {
|
||||
console.log("Failed!");
|
||||
console.error(err);
|
||||
});
|
||||
|
||||
|
||||
wss.on("connection", socket => {
|
||||
// Stream for incoming WebSocket messages
|
||||
const messageStream = new Readable({ objectMode: true });
|
||||
messageStream._read = () => {};
|
||||
|
||||
socket.on("message", (message: string) => {
|
||||
messageStream.push(JSON.parse(message));
|
||||
});
|
||||
|
||||
|
||||
/**
|
||||
* Daemon and bridge are the same binary, so spawn a new
|
||||
* version of self in bridge mode.
|
||||
*/
|
||||
const bridge = spawn(process.execPath, [ process.argv[1] ]);
|
||||
|
||||
// socket -> bridge.stdin
|
||||
messageStream
|
||||
.pipe(new EncodeTransform())
|
||||
.pipe(bridge.stdin);
|
||||
|
||||
// bridge.stdout -> socket
|
||||
bridge.stdout
|
||||
.pipe(new DecodeTransform())
|
||||
.on("data", data => {
|
||||
// Socket can be CLOSING here
|
||||
if (socket.readyState === WebSocket.OPEN) {
|
||||
socket.send(JSON.stringify(data));
|
||||
}
|
||||
});
|
||||
|
||||
// Handle termination
|
||||
socket.on("close", () => bridge.kill());
|
||||
bridge.on("exit", () => socket.close());
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user