69

Node.JS进程间通讯的几种方法:Redis Publish/Subscribe 和 UDP Socket

 6 years ago
source link: http://ourjs.com/detail/5b742ca09ed90647f8af6199?amp%3Butm_medium=referral
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

借助 Redis

如果您装有redis客户端就可以通过 redis 的 publish/ subscribe方法来实现进程间通讯,注意一旦使用subscribe,则此 redis 只能接收:SUBSCRIBE、PSUBSCRIBE、UNSUBSCRIBE和PUNSUBSCRIBE 等消息订阅指令,您可以专门创建一个redis实例来进行进程间通信。 

var redis = require("redis");
var sub = redis.createClient();

sub.on("message", function (channel, message) {
    console.log("sub channel " + channel + ": " + message);
    msg_count += 1;
    if (msg_count === 3) {
        sub.unsubscribe();
        sub.quit();
        pub.quit();
    }
});

sub.subscribe("a nice channel");

发送端:

var redis = require("redis");
var pub = redis.createClient();

pub.publish("a nice channel", "I am sending a message.");

借助 UDP Socket

如果是本机之间通信,则直接使用node.js内置的udp通信模块就可以了,几乎不会发生丢包问题,实现也非常简单:

发送端:

var dgram = require('dgram')
var client = dgram.createSocket('udp4')
client.send('This is message', 889, '127.0.0.1')

接收端:注意绑定端口需要和发送端的保持一致

var dgram = require('dgram');
var messager = dgram.createSocket('udp4');

messager.on('message', function (msg, rinfo) {
  if (rinfo.address != '127.0.0.1') {
    console.log('非本机消息,忽略,防止恶意消息')
    return
  }

  console.log('rinfo', rinfo)
  console.log('messager got: ', msg.toString());
});

messager.bind(889);

输出:

rinfo { address: '127.0.0.1', family: 'IPv4', port: 55402, size: 15 }
messager got:  This is message

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK