Node.js Inter process communication?

梦想与她 提交于 2020-05-29 05:41:07

问题


Does Node.js provide any standard way of doing IPC as it happens in many other languages? I am new to Node.js and all information I found was about using child_process.fork() or sockets.


回答1:


Have you tried this node package?

Following their doc, possible example could be for server:

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();

possible solution for client:

 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);
            }
        );
    }
);


来源:https://stackoverflow.com/questions/22022539/node-js-inter-process-communication

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!