需要用到网络通信时,ZeroMQ( 简称ZMQ )比较方便,他提供了许多对服务端和客户端之间的通信方式:REP/REQ、PULL/PUSH( 应用这两个就能实现比较简单的数据查询与发送功能 ), 具体有方式在ZMQ的jar包的ZMQ.class 中可以看到,都是通过定义为int常量,如下:

 1     public static final int PUB = 1;
 2     public static final int SUB = 2;
 3 
 4     public static final int REQ = 3;
 5     public static final int REP = 4;
 6 
 7     public static final int DEALER = 5;
 8 
 9     public static final int XREQ = 5;
10     public static final int XREP = 6;
11 
12     public static final int ROUTER = 6;
13 
14 
15     public static final int PULL = 7;
16     public static final int PUSH = 8;
17 
18     public static final int XPUB = 9;
19     public static final int XSUB = 10;
20 
21     public static final int STREAMER = 1;
22     public static final int FORWARDER = 2;
23 
24     public static final int QUEUE = 3;
25 
26     public static final int UPSTREAM = 7;
27     public static final int DOWNSTREAM = 8;

 

下面就以REQ/REP为例进行简单的说明。

REQ( Request ) 和REP( Response )进行编程时,首先需要建立一个REP,并开始接受请求,在收到请求之后需要对请求进行处理,处理完返回处理结果即可,代码如下:

 1     public static void main(String[] argv) {
 2         ZMQ.Context context = ZMQ.context(1);
 3         ZMQ.Socket socket = context.socket(ZMQ.REP);
 4         String url = "tcp://*:9999";
 5         try {
 6             socket.bind(url);
 7         } catch (ZMQException e) {
 8             throw e;
 9         }
10         boolean wait = true;
11         while (wait) {
12             byte[] request;
13             try {
14                 request = socket.recv(0);
15 
16 
17                 /* TODO process request
18                  * .....
19                 */
20                 socket.send("OK".getBytes(), 1);
21 
22             } catch (ZMQException e) {
23                 throw e;
24             }
25         } // while(wait)
26     }

客户端在通过REQ进行编程时,需要把请求通过byte类型( 需要与服务端接收请求的类型一至,一般用byte,官网上的示例代码是这样的,而且一般都以\0 表示结束 )发送过去,之后等待响应。代码如下:

 1     public static void main(String[] args) {
 2         ZMQ.Context context = ZMQ.context(1);
 3         ZMQ.Socket socket = context.socket(ZMQ.REQ);
 4 
 5         System.out.println("Connecting to hello world server...");
 6         socket.connect("tcp://localhost:9999");
 7 
 8         String requestString = "Hello" + " ";
 9         byte[] request = requestString.getBytes();
10         socket.send(request, 0);
11 
12         byte[] reply = socket.recv(0);
13         System.out.println("Received reply   [" + new String(reply) + "]");
14     }

 

注:官方给的示例代码中在send和recv方法中传int类型值的时候都是用0, 在ZMQ类中有一个变量public static final int PAIR = 0, 可能就是这个变量吧,说明在通信过程中是要相互匹配的( 如REQ和REP要一起工作, 个人猜想 ),否则在工作过程中是会抛异常的。

官方在git上的代码位置为: https://github.com/imatix/zguide2

 posted on 2012-11-12 17:36  小枫晚归  阅读(8272)  评论(0编辑  收藏  举报