简体   繁体   English

Node.js 和 Java 之间的 IPC 通信

[英]IPC Communication between Node.js and Java

I'm looking to communicate between Node.js and a Java sub-process via IPC.我希望通过 IPC 在 Node.js 和 Java 子进程之间进行通信。 I'm looking for recommendations that do not require opening a port.我正在寻找不需要打开端口的建议。

const { spawn } = require('child_process')

// Java App is within args
const args = []

const javaProcess = spawn('java', args, { cwd: __dirname })

javaProcess.on('message', (m) => {
  console.log('PARENT got message:', m)
})

// Sends { 'hello': 'world' } to the Java process
javaProcess.send({ hello: 'world' })

I understand that the Node layer can send messages to a sub-process, I just don't know how I'd go about listening for messages in the Java layer and sending messages back.我知道 Node 层可以将消息发送到子进程,我只是不知道如何在 Java 层中侦听消息并发送回消息。

Any help is greatly appreciated, thanks!非常感谢任何帮助,谢谢!

I ended up solving this with inspiration from Erwin Bolwidt's Comment .我最终从Erwin Bolwidt 的 Comment中得到灵感解决了这个问题。

const { spawn } = require('child_process')

// Java App is within args
const args = []

const javaProcess = spawn('java', args, { cwd: __dirname })

javaProcess.stdout.on('data', (m) => {
  console.log('PARENT got message:', m)
})

// Sends message to the Java process
javaProcess.stdin.write('Hello there java!');

The java process can wait for a message with a Scanner on System.in then print output to System.out . java 进程可以在System.in上等待带有Scanner的消息,然后将输出打印到System.out

In summary you're just rerouting the process's stdin/stdout.总之,您只是重新路由进程的标准输入/标准输出。 https://nodejs.org/api/child_process.html#subprocessstdout https://nodejs.org/api/child_process.html#subprocessstdout

I solved this issue by using named pipes...我通过使用命名管道解决了这个问题......

On Node I used the Net API https://nodejs.org/api/net.html#net_ipc_support在节点上,我使用了 Net API https://nodejs.org/api/net.html#net_ipc_support

On Java I used RandomAccessFile https://docs.oracle.com/javase/7/docs/api/java/io/RandomAccessFile.html在 Java 上,我使用了 RandomAccessFile https://docs.oracle.com/javase/7/docs/api/java/io/RandomAccessFile.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM