質問はタイトルにありますが、少し詳しく説明します。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);
}
}
}