Node.js 进程间通信?

use*_*528 7 ipc node.js

Node.js 是否像在许多其他语言中那样提供任何标准的 IPC 方法?我是 Node.js 的新手,我发现的所有信息都是关于使用 child_process.fork() 或套接字。

ale*_*xey 6

你试过这个节点包吗?

按照他们的文档,可能的示例可能是服务器:

var ipc=require('node-ipc');

ipc.config.id   = 'world';
ipc.config.retry= 1500;

ipc.serve(
    function(){
        ipc.server.on(
            'message',
            function(data,socket){
                ipc.log('got a message : '.debug, data);
                ipc.server.emit(
                    socket,
                    'message',  //this can be anything you want so long as
                                //your client knows.
                    data+' world!'
                );
            }
        );
    }
);

ipc.server.start();
Run Code Online (Sandbox Code Playgroud)

客户可能的解决方案:

 var ipc=require('node-ipc');

ipc.config.id   = 'hello';
ipc.config.retry= 1500;

ipc.connectTo(
    'world',
    function(){
        ipc.of.world.on(
            'connect',
            function(){
                ipc.log('## connected to world ##'.rainbow, ipc.config.delay);
                ipc.of.world.emit(
                    'message',  //any event or message type your server listens for
                    'hello'
                )
            }
        );
        ipc.of.world.on(
            'disconnect',
            function(){
                ipc.log('disconnected from world'.notice);
            }
        );
        ipc.of.world.on(
            'message',  //any event or message type your server listens for
            function(data){
                ipc.log('got a message from world : '.debug, data);
            }
        );
    }
);
Run Code Online (Sandbox Code Playgroud)