Java 使用ZeroMQ 2.2 進行通信編程


需要用到網絡通信時,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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM