0
我正在嘗試製作一個帶有Java FXML接口以及用於製作音頻播放機器人的Node.js程序的Discord機器人。Java啓動Node.js程序立即關閉
當我嘗試打開Java內的Node.js進程時,我注意到它立即關閉,因爲當我嘗試寫入時,出現IOException pipes are being closed
。我不確定爲什麼會發生這種情況,因爲當我在命令行中運行節點時,它完全保持打開狀態。有誰知道我的程序爲什麼立即關閉?
Node.js的通信類:
public class NodeCommunicationHandler {
private static final Logger LOG = Logger.getLogger(NodeCommunicationHandler.class.getName());
private Process nodeProcess;
private ExecutorService threadPool;
private ProcessHandlerTask callbackHandler;
private StringProperty callback;
private OutputStream writeStream;
/**
*
*/
public NodeCommunicationHandler() {
try {
// Activate Node.js sub-process
this.nodeProcess = new ProcessBuilder("cmd", "/c", "start", "node", "\"" + Reference.NODE_PROGRAM_LOCATION + "\"").start();
// Initialize the stdout writing stream
this.writeStream = this.nodeProcess.getOutputStream();
// Initialize the stdin reader on the process
this.callbackHandler = new ProcessHandlerTask(this.nodeProcess);
// Bind the callback data from the process to the callback property
this.callback = new SimpleStringProperty();
this.callback.bind(this.callbackHandler.messageProperty());
// Run the thread of the process callback handler
this.threadPool = Executors.newFixedThreadPool(2);
this.threadPool.submit(this.callbackHandler);
} catch (IOException ex) {
NodeCommunicationHandler.LOG.log(Level.SEVERE, null, ex);
}
}
/**
* Retrieve the internal process callback.
*
* @return The callback.
*/
public StringProperty getCallback() {
return this.callback;
}
/**
* Writes a string command to the Node.js process.
*
* @param command The command to write.
*/
public void write(String command) {
try {
this.writeStream.write(command.getBytes());
this.writeStream.flush();
} catch (IOException ex) {
NodeCommunicationHandler.LOG.log(Level.SEVERE, null, ex);
}
}
/**
* Stop the Node.js process
*/
public void stop() {
try {
// Write the command STOP towards the node process to promptly exit the discord API.
this.write("STOP");
// Close the writing stream since STOP is the last command we have to write.
this.writeStream.close();
// Wait for the Node.js acknowledgement of the STOP issue.
NodeProcessExitHandler exitCond = new NodeProcessExitHandler(this.callback);
this.threadPool.submit(exitCond).get();
// Unbind the callback listener.
this.callback.unbind();
// Stop the callback handler and let the thread finish.
this.callbackHandler.stop();
// Keep the process alive until the callback handler has been disconnected.
this.threadPool.awaitTermination(10000, TimeUnit.MILLISECONDS);
// Kill the subprocess since we know
this.nodeProcess.destroy();
} catch (IOException | InterruptedException | ExecutionException ex) {
NodeCommunicationHandler.LOG.log(Level.SEVERE, null, ex);
}
}
}
而且我的JavaScript程序:
var stdin = process.openStdin();
stdin.addListener("data", function(d) {
console.log("You entered: " + d.toString());
});
的JavaScript是很基本的,但它應該能夠提供我所需要的。
編輯:
問題描述中的小錯誤。 當進程以Java運行時,它會打開一個控制檯窗口,並且Node程序實際上保持運行,但Outputstream只是斷開連接並引發IOException。