サーバと同様にクライアントのプロジェクトを作成します。
以下のようにプロジェクトが作成されます。
次に、動作させるサーバを作成します。ここでは、パッケージをremoting.server.testとします。
simpleJBossRemotingServer/src配下に以下のサーバアプリケーションのクラスを作成します。
package remoting.server.test;
import org.jboss.remoting.InvokerLocator;
import org.jboss.remoting.transport.Connector;
/**
* 受信したメッセージを表示し、受信した旨のメッセージを送信するサーバクラス
*/
public class SimpleServer {
public static void main(String[] args) throws Exception {
InvokerLocator myLocator = new InvokerLocator("socket://127.0.0.1:8888");
Connector connector = new Connector();
connector.setInvokerLocator(myLocator.getLocatorURI());
connector.start();
connector.addInvocationHandler("simpleSystem",new SimpleServerInvocationHandler());
try {
while (true) {
Thread.sleep(1000);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
SimpleServerクラスでは、まず以下で接続方法を定義しています。InvokerLocatorクラスによって自動的にsocketで接続を行います。
InvokerLocator myLocator = new InvokerLocator("socket://127.0.0.1:8888");
次に、定義した接続方法を用いて接続の待ち受け状態となります。
Connector connector = new Connector();
connector.setInvokerLocator(myLocator.getLocatorURI());
connector.start();
最後に、クライアントからのメソッド呼び出しの動作について設定しています。
connector.addInvocationHandler("simpleSystem",new SimpleServerInvocationHandler());
メソッド呼び出しのためのハンドラとしてSimpleServerInvocationHandlerクラスについて説明します。
package remoting.server.test;
import javax.management.MBeanServer;
import org.jboss.remoting.InvocationRequest;
import org.jboss.remoting.ServerInvocationHandler;
import org.jboss.remoting.ServerInvoker;
import org.jboss.remoting.callback.InvokerCallbackHandler;
/**
* メソッド呼び出しのためのハンドラ
*/
public class SimpleServerInvocationHandler implements ServerInvocationHandler {
/**
* 受信したメッセージを処理し、メッセージを返却します。
*/
public Object invoke(InvocationRequest invocation) {
System.out.println(" request:「" + invocation.getParameter() + "」");
return "ServerからClientへ";
}
public void addListener(InvokerCallbackHandler arg0) {
}
public void removeListener(InvokerCallbackHandler arg0) {
}
public void setInvoker(ServerInvoker arg0) {
}
public void setMBeanServer(MBeanServer arg0) {
}
}
SimpleServerInvocationHandlerクラスでは、リモート呼び出しが実行されるinvokeメソッドを実装します。
System.out.println(" request:「" + invocation.getParameter() + "」");
最後に、呼び出し元へ処理結果を返却します。
return "ServerからClientへ";
次ページでは最後に、クライアントのクラスを実装し、実際に動作確認してみましょう。jBoss Remotingによるさまざまな接続方法も紹介します。
Copyright © ITmedia, Inc. All Rights Reserved.