我正在尝试使用下图中提供的 XPUB 和 XSUB 来实现。我已经浏览了他们提供的示例,但在 Java 中找不到用于 XPUB 和 XSUB 的示例。在这里,他们给出了一个 C 语言的例子,因为我是 ZeroMQ 的新手,所以它有点复杂。
我正在尝试使用jni 包装版本在 android 中使用它。请帮我找一个例子,如何使用 java 在 ZeroMQ 中使用代理实现这个 Pub-Sub 网络。
目前我指的是http://zguide.zeromq.org/page:all
我试图将其移植如下。 订阅者.java
公共类订阅者扩展线程实现可运行{private static final String TAG = "Subscriber"; private Context ctx; public Subscriber(ZMQ.Context z_context) { this.ctx = z_context; } @Override public void run() { super.run(); ZMQ.Socket mulServiceSubscriber = ctx.socket(ZMQ.SUB); mulServiceSubscriber.connect("tcp://localhost:6001"); mulServiceSubscriber.subscribe("A".getBytes()); mulServiceSubscriber.subscribe("B".getBytes()); while (true) { Log.d(TAG, "Subscriber loop started.."); String content = new String(mulServiceSubscriber.recv(0)); Log.d(TAG, "Subscriber Received : "+content); } }
}
Publisher.java
公共类发布者扩展线程实现可运行{private static final String TAG = "Publisher"; private Context ctx; public Publisher(ZMQ.Context z_context) { this.ctx = z_context; } @Override public void run() { super.run(); ZMQ.Socket publisher = ctx.socket(ZMQ.PUB); publisher.connect("tcp://localhost:6000"); while (true) { Log.d(TAG, "Publisher loop started.."); publisher.send(("A Hello " + new Random(100).nextInt()).getBytes() , 0); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } }
}
XListener.java(现在是一个简单的转发器)
公共类 XListener 扩展 Thread 实现 Runnable {private static final String TAG = null; private Socket publisherX; private Context ctx; private Socket subscriberX; public XListener(ZMQ.Context ctx, ZMQ.Socket subscriberX, ZMQ.Socket publisherX) { this.ctx = ctx; this.subscriberX = subscriberX; this.publisherX = publisherX; } @Override public void run() { super.run(); while (true) { Log.d(TAG, "XListener loop started.."); String msg = new String(subscriberX.recvStr()); Log.v(TAG, "Listener Received: " +"MSG :"+msg); publisherX.send(msg.getBytes(), 0); } }
}
在应用程序main()
私人无效主要(){
ZMQ.Context ctx = ZMQ.context(1);
ZMQ.Socket subscriberX = ctx.socket(ZMQ.XSUB);
subscriberX.bind("tcp://*:6000");
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ZMQ.Socket publisherX = ctx.socket(ZMQ.XPUB);
publisherX.bind("tcp://*:6001");
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
new XListener(ctx, subscriberX, publisherX).start();
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
new XSender(ctx, subscriberX, publisherX).start();
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
new Subscriber(ctx).start();
new Publisher(ctx).start();
}
使用代码我无法收听XSUB。在移植espresso.c时,我无法在 ZMQ 的 java 绑定中找到任何包装器。如何实现一个简单的代理或者我错过了什么?