ZeroMQ之REP/REQ模式

参考: http://zguide.zeromq.org/page:all

REP/REQ这种模式是双向的,应答模式。也就是说是一个请求一个响应,不能发送多个消息。

模型的图如下:(图源自于 http://zguide.zeromq.org/page:all )

代码如下:

服务器代码:

package reqrep;

import org.zeromq.ZMQ;

public class REP {

    /**
     * @param args
     * @throws InterruptedException 
     */
    public static void main(String[] args) throws InterruptedException {
	// TODO Auto-generated method stub
	ZMQ.Context context = ZMQ.context(1);
	ZMQ.Socket s = context.socket(ZMQ.REP);
	s.bind("tcp://*:5557");
	int i = 0;
	while (true) {
	    i++;
	    String msg = new String(s.recv(0));
	    s.send((msg + "_rep"+i).getBytes(), 0);
	}
    }

}

 

客户端代码:

 

package reqrep;

import org.zeromq.ZMQ;

public class REQ {
    /**
     * @param args
     * @throws InterruptedException 
     */
    public static void main(String[] args) throws InterruptedException {
	// TODO Auto-generated method stub
	ZMQ.Context context = ZMQ.context(1);
	ZMQ.Socket s = context.socket(ZMQ.REQ);
	s.connect("tcp://*:5557");
	int i = 0;
	while (true) {
	    Thread.currentThread().sleep(2000);
	    s.send(("msg" + "_req").getBytes(), 0);
	    String rev = new String(s.recv(0));
	    System.out.println(rev);
	}
    }

}

 

结果:

msg_req_rep1
msg_req_rep2
msg_req_rep3
msg_req_rep4
msg_req_rep5
msg_req_rep6
msg_req_rep7
msg_req_rep8
...

 

显然这种应答模式的效率很低!

猜你喜欢

转载自lbxc.iteye.com/blog/1533733
今日推荐