2

问题在标题中,但要详细说明。如果我使用 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);
        }
    }
}
4

1 回答 1

2

ZMQ 支持这种行为(允许客户端在服务器启动之前订阅等),因为它产生了一个单独的线程来处理套接字通信。如果套接字的端点不可用,则线程负责对请求进行排队,直到连接可用。这一切都是为您透明地完成的。

因此,当然,您可以将这种技术用于其他 API,但您必须自己处理所有繁重的工作。

于 2012-02-21T01:25:58.007 回答