No messages match using SUB in Java with ZeroMQ

2019-06-13 03:57发布

问题:

I'm trying to use Java client with ZeroMQ. When subscribing to any prefix, the Java client matches no messages, although a similar Python client matches messages as expected.

The Python server

context = zmq.Context()
socket = context.socket(zmq.PUB)
socket.bind("tcp://*:5556")

for i in range(100):
    r = "XXX " + i
    socket.send_string(r)

    time.sleep(random.randint(0,10))

The Python client working fine

context = zmq.Context()
socket = context.socket(zmq.SUB)
socket.connect("tcp://localhost:5556")

zip_filter = "XXX"
socket.setsockopt_string(zmq.SUBSCRIBE, zip_filter)

for update_nbr in range(5):
    s = socket.recv_string()
    print(s)

The Java client matching no messages

context = ZMQ.context(1);
subscriber = context.socket(ZMQ.SUB);
subscriber.connect("tcp://localhost:5556");

String filter = "XXX";
subscriber.subscribe(filter.getBytes(Charset.forName("UTF-8")));
while (true) {
  String msg = subscriber.recvStr(0, Charset.forName("UTF-8"));
  // ...
}

Using the above Python server, the Python client matches all messages starting with XXX as expected.

Using the same Python server, the Java client matches no messages.

Do you have any idea what is wrong with the call to subscribe() in the Java client?

回答1:

Ok, so I've recreated your configuration and sadly, everything works fine - both in python and java. (here's the proof) )

Java code:

public class Client {

    public static void main(String[] args) {
        final Context context = context(1);
        final Socket subscriber = context.socket(SUB);
        subscriber.connect("tcp://localhost:5556");

        String filter = "XXX";
        subscriber.subscribe(filter.getBytes(Charset.forName("UTF-8")));
        while (true) {
            String msg = subscriber.recvStr();
            System.out.println(msg);
        }
    }
}

Maven dependency:

<dependency>
    <groupId>org.zeromq</groupId>
    <artifactId>jeromq</artifactId>
    <version>0.3.4</version>
</dependency>

zeromq version: 4.1.0

What version of jeromq do you use? I don't even have a method recvStr(int, Java.nio.charset.Charset).