问题描述:
在之前的例子中我们没有使用特别的TOPIC来区分,这次我们对发布的消息进行TOPIC区分,但是发现这个TOPIC不能存在一个相似度,看如下代码:
package com.guo.server;
import org.zeromq.ZMQ;import org.zeromq.ZMQ.Context;import org.zeromq.ZMQ.Socket;public class Publisher { public void start(){ System.out.println("===========publisher start============="); Context context = ZMQ.context(1); Socket socket = context.socket(ZMQ.PUB); socket.setLinger(5000); socket.setSndHWM(0); socket.bind("tcp://192.168.124.130:6666"); try { Thread.sleep(10000); } catch (InterruptedException e) { } for(int i=0;i<10;i++){ String pubstr ="WORK task"+i; socket.sendMore("NEWS"); socket.send(pubstr); socket.sendMore("NEWSONE"); socket.send("can not receive"); try { Thread.sleep(1000); } catch (InterruptedException e) { } } socket.send("END", 0); System.out.println("===========publisher end============="); socket.close(); context.term(); }}这里发布了2个TOPIC,然而订阅端做了一个订阅package com.guo.client;
import org.zeromq.ZMQ;import org.zeromq.ZMQ.Context;import org.zeromq.ZMQ.Socket;public class Subscriber { public void start(){ System.out.println("===========subscriber start============="); Context context = ZMQ.context(1); Socket socket = context.socket(ZMQ.SUB); socket.connect("tcp://192.168.124.130:6666"); socket.subscribe("NEWS".getBytes()); while(true){ byte[] top =socket.recv(0); String topStr = new String(top); byte[] res =socket.recv(0); String resStr = new String(res); System.out.println("substring is ="+topStr+" "+resStr); if("END".equalsIgnoreCase(resStr)){ break; } } System.out.println("===========subscriber end============="); socket.close(); context.term(); }}结果是两个主题都有消息接收。如果将发布的代码调整为:socket.sendMore("NEWS");
socket.send(pubstr); socket.sendMore("ONE");这样订阅端可以正常使用。经测试个人认为这是使用正则造成的一个小的BUG,问题待日后求证。
这里如果发布端采用单一的发送方式:socket.send(pubstr);则在订阅端我们可以通过订阅WORK主题来得到完整的消息:socket.subscribe("WORK".getBytes());byte[] res =socket.recv(0);如果这里的订阅主题换成其他的则是得不到消息的。
上述代码结束有点问题,请忽略一下。