2012-01-13 4 views
2

質問はタイトルにありますが、少し詳しく説明します。 Sun/Oracle NIO APIまたはNettyのようなフレームワークを使用してJavaでNIOアプリケーションを作成している場合、接続するホスト/ポートにバインドされたサーバーがない場合でも、クライアントをサブスクライバとして「接続」することは可能ですかに?私が効果的にやりたいことは、サーバーが死んでいても、それがオンラインになってすぐにメッセージが送信されても​​、それがそこにあるかのように受け取ります。このZMQサーバとクライアントを例えば最初のクライアントを起動するサーバが稼働する前にクライアントが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); 
     } 
    } 
} 

答えて

2

ZMQは(前に、など、クライアントが購読できるように、この動作をサポートしていますサーバーは稼動しています)。これは、ソケット通信を処理するための別のスレッドを生成するためです。ソケットのエンドポイントが利用できない場合、スレッドは接続が利用可能になるまでキューイング要求を処理します。これはすべてあなたのために透過的に行われます。

確かに、この手法を他のAPIに採用することは可能でしょうが、すべての面倒な作業そのものを処理する必要があります。

関連する問題