云端轻躺 2010-08-02
反射,客户端服务器.
接口实现类(传递的中间类)
publicinterfaceHelloService
publicclassHelloServiceImplimplementsHelloService
publicclassCallimplementsSerializable
publicclassSimpleServer{
privateMapremoteObjects=newHashMap();//存放远程对象的缓存
/**把一个远程对象放到缓存中*/
publicvoidregister(StringclassName,ObjectremoteObject){
remoteObjects.put(className,remoteObject);
}
publicvoidservice()throwsException{
ServerSocketserverSocket=newServerSocket(8000);
System.out.println("服务器启动.");
while(true){
Socketsocket=serverSocket.accept();
InputStreamin=socket.getInputStream();
ObjectInputStreamois=newObjectInputStream(in);
OutputStreamout=socket.getOutputStream();
ObjectOutputStreamoos=newObjectOutputStream(out);
Callcall=(Call)ois.readObject();//接收客户发送的Call对象
System.out.println(call);
call=invoke(call);//调用相关对象的方法
oos.writeObject(call);//向客户发送包含了执行结果的Call对象
ois.close();
oos.close();
socket.close();
}
}
publicCallinvoke(Callcall){
Objectresult=null;
try{
StringclassName=call.getClassName();
StringmethodName=call.getMethodName();
Object[]params=call.getParams();
ClassclassType=Class.forName(className);
Class[]paramTypes=call.getParamTypes();
Methodmethod=classType.getMethod(methodName,paramTypes);
ObjectremoteObject=remoteObjects.get(className);//从缓存中取出相关的远程对象
if(remoteObject==null){
thrownewException(className+"的远程对象不存");
}else{
result=method.invoke(remoteObject,params);
}
}catch(Exceptione){result=e;}
call.setResult(result);//设置方法执行结果
returncall;
}
publicstaticvoidmain(Stringargs[])throwsException{
SimpleServerserver=newSimpleServer();
//把事先创建的HelloServiceImpl对象加入到服务器的缓存中
server.register("remotecall.HelloService",newHelloServiceImpl());
server.service();
}
publicclassSimpleClient{
publicvoidinvoke()throwsException{
Socketsocket=newSocket("localhost",8000);
OutputStreamout=socket.getOutputStream();
ObjectOutputStreamoos=newObjectOutputStream(out);
InputStreamin=socket.getInputStream();
ObjectInputStreamois=newObjectInputStream(in);
//Callcall=newCall("remotecall.HelloService","getTime",
newClass[]{},newObject[]{});
Callcall=newCall("remotecall.HelloService","echo",
newClass[]{String.class},newObject[]{"Hello"});
oos.writeObject(call);//向服务器发送Call对象
call=(Call)ois.readObject();//接收包含了方法执行结果的Call对象
System.out.println(call.getResult());
ois.close();
oos.close();
socket.close();
}
publicstaticvoidmain(Stringargs[])throwsException{
newSimpleClient().invoke();
}
}