一个JNDI context lookup的问题,望高手不吝赐教!!!

04-04-01 vampire
本人写了这样一个RMI-IIOP程序,为测试一下如下功能:

用户输入几个IP地址,从这里面查找哪些Server端当前可用,哪些不可用。

//Server.java

import java.util.*;

import java.rmi.Remote;

import java.rmi.RemoteException;

import javax.rmi.PortableRemoteObject;

import javax.naming.Context;

import javax.naming.InitialContext;

public class Server extends PortableRemoteObject implements RMIInterface {

public Server() throws RemoteException {

}

// implementation of RMIInterface methods

public String showWelcome() throws RemoteException {

return "Welcome!!!";

}

public static void main(String[] args) {

try {

Hashtable env=new Hashtable();

env.put("java.naming.factory.initial","com.sun.jndi.cosnaming.CNCtxFactory");

env.put("java.naming.provider.url","iiop://localhost:1050");

Server s = new Server();

// create the naming context

Context initialNamingContext = new InitialContext(env);

initialNamingContext.rebind("Server", s );

System.out.println("Server waiting...");

} catch (Exception e) {

e.printStackTrace();

}

}

//Client.java

import javax.rmi.PortableRemoteObject;

import javax.naming.Context;

import javax.naming.InitialContext;

import java.util.*;

public class Client {

static Hashtable env[] = new Hashtable[4];

static int i=0;

public static void search(Hashtable env1){

try{

SerClass se = new SerClass(env1.toString());

// get the naming context

Context ic = new InitialContext(env1);

// get a reference to the remote object

Object objRef = ic.lookup("Server");

ic.close() ;

// narrow it into our RMIInterface

RMIInterface ri =

(RMIInterface) PortableRemoteObject.narrow(objRef, RMIInterface.class);

//invoke RMIInterface method

System.out.println("Recieved from server: " + ri.showWelcome() + "\n");

// display agent is valid or invalid

System.out.println("Valid Agent:" + se.getIp() + "\n");

}

catch (Exception e) {

System.out.println("invalid Agent");

}

finally{

if(i<3)

search(env[++i]);

}

}

public static void main(String[] args) {

for(int n=0;n<args.length ;n++){

env[n]=new Hashtable();

env[n].put("java.naming.factory.initial",

"com.sun.jndi.cosnaming.CNCtxFactory");

env[n].put("java.naming.provider.url", "iiop://" + args[n] + ":1050");

}

search(env[0]);

}

}

当前采用的方法是不管Server端开不开服务都尝试连接一下,如果连上了就显示valid agent;若产生异常则说明是invalid。

现在的问题是:在连接不可用的Server时要过比较长的时间才能显示出invalid agent,不知是不是有设置lookup timeout的方法或者采取另一种更好的机制来实现查找Server端可用性的方法。望高手不吝赐教!!!

猜你喜欢