问题在标题中,但要详细说明。如果我使用 Sun/Oracle NIO API 或 Netty 等框架在 Java 中编写 NIO 应用程序,即使没有服务器绑定到它连接的主机/端口,是否也可以让客户端“连接”为订阅者到?我实际上想要做的只是不在乎服务器是否死机,但只要它在线并发送消息,我就会收到它,就好像它一直都在那里一样。以这个 ZMQ 服务器和客户端为例
首先启动客户端......
import org.zeromq.ZMQ;
import java.util.Date;
public class ZMQClient {
public static void main(String[] args) {
// Prepare our context and subscriber
ZMQ.Context context = ZMQ.context(1);
ZMQ.Socket subscriber = context.socket(ZMQ.SUB);
subscriber.connect("tcp://localhost:5563");
subscriber.subscribe("".getBytes());
while (true) {
// Read envelope with address
String address = new String(subscriber.recv(0));
// Read message contents
String contents = new String(subscriber.recv(0));
System.out.println(address + " : " + contents+" - "+ new Date());
}
}
}
...一段时间后服务器
import org.zeromq.ZMQ;
import java.util.Date;
public class ZMQServer {
public static void main(String[] args) throws Exception{
// Prepare our context and publisher
ZMQ.Context context = ZMQ.context(1);
ZMQ.Socket publisher = context.socket(ZMQ.PUB);
publisher.bind("tcp://127.0.0.1:5563");
while (true) {
// Write two messages, each with an envelope and content
publisher.send("".getBytes(), ZMQ.SNDMORE);
publisher.send("We don't want to see this".getBytes(), 0);
publisher.send("".getBytes(), ZMQ.SNDMORE);
publisher.send("We would like to see this".getBytes(), 0);
System.out.println("Sent @ "+new Date());
Thread.sleep(1000);
}
}
}