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 に答える