java - zmq 如何允许客户端在服务器启动之前订阅/收听

标签 java publish-subscribe zeromq jzmq

问题在标题中,但要详细说明一下。如果我使用 Sun/Oracle NIO API 或类似 Netty 的框架在 Java 中编写 NIO 应用程序,是否可以让客户端作为订阅者“连接”,即使没有服务器绑定(bind)到它连接的主机/端口到?我实际上想做的是不关心服务器是否已死,但只要它在线并发送一条消息,我就会收到它,就好像它一直都在那里一样。以这个 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);
        }
    }
}

最佳答案

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

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

关于java - zmq 如何允许客户端在服务器启动之前订阅/收听,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8857982/

相关文章:

java - Android XML 文件 java.lang.nullpointerexception

java - PreparedStatement

java - SBT(简单构建工具): Change the build target "classes" directory

meteor - Meteor 的 DDP 在同步大型集合方面的效率如何?

javascript - 当我在服务器上进行过滤时,为什么我的 Meteor.js 发布没有返回任何结果?

image - ZeroMQ pyzmq通过tcp发送jpeg图像

python - 更改 IPC ://to tcp://python zmq (Windows)

java - 非法状态异常 : zip file closed during file write

javascript - 为什么 "opener.$(document).trigger(' 自定义 ')"不起作用?

node.js - ZMQ 套接字在 Kubernetes 上无法按预期工作