Question

The question is in the title but to elaborate a bit. If I'm writing an NIO application in Java using the Sun/Oracle NIO APIs or a framework like Netty, is it possible to have a client "connect" as a subscriber even while there is no server bound to the host/port it connects to? What I effectively want to do is just not care if the server is dead but as soon as it is online and sends a message I receive it as if it was there the whole time. Take this ZMQ server and client for e.g.

Starting the client first....


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());
        }
    }
}

...and some time later the server


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);
        }
    }
}
Was it helpful?

Solution

ZMQ supports this behavior (allowing clients to subscribe, etc., before the server is up) because it spawns a separate thread for handling socket communication. If the endpoint of the socket is not available, the thread takes care of queuing requests until the connection becomes available. This is all done transparently for you.

So, sure, you could probably adopt this technique for other APIs, but you'd have to take care of all the grunt work itself.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top