socket 在远程方法调用中运用反射机制

反射,客户端 服务器.

接口 实现类 (传递的中间类)



public interface HelloService

public class HelloServiceImpl implements HelloService

public class Call implements Serializable



public class SimpleServer {
private Map remoteObj ects=new HashMap(); //存放远程对象的缓存

/** 把一个远程对象放到缓存中*/
public void register(String className,Object remoteObj ect){
remoteObj ects.put( className,remoteObj ect);
}

public void service()throws Exception{
ServerSocket serverSocket = new ServerSocket(8000);
System.out.println("服务器启动.");
while(true){
Socket socket=serverSocket.accept();
InputStream in=socket.getInputStream();
Obj ectInputStream ois=new Obj ectInputStream(in);
OutputStream out=socket.getOutputStream();
Obj ectOutputStream oos=new Obj ectOutputStream(out);

Call call=(Call)ois.readObj ect(); //接收客户发送的Call 对象
System.out.println(call);
call=invoke(call); //调用相关对象的方法
oos.writeObj ect(call); // 向客户发送包含了执行结果的Call 对象

ois.close();
oos.close();
socket.close();
}
}

public Call invoke(Call call){

Obj ect result=null;
try{
String className=call.getClassName();
String methodName=call.getMethodName();
Obj ect[] params=call.getParams();
Class classType=Class.forName(className);
Class[] paramTypes=call.getParamTypes();
Method method=classType.getMethod(methodName,paramTypes);
Obj ect remoteObj ect=remoteObj ects.get(className); //从缓存中取出相关的远程对象
if(remoteObj ect==null){
throw new Exception(className+"的远程对象不存 ");
}else{
result=method.invoke(remoteObject,params);
}
}catch(Exception e){result=e;}

call.setResult(result); //设置方法执行结果
return call;
}

public static void main(String args[])throws Exception {
SimpleServer server=new SimpleServer();
//把事先创建的HelloServiceImpl 对象加入到服务器的缓存中
server.register("remotecall.HelloService",new HelloServiceImpl());
server.service();
}



public class SimpleClient {
public void invoke()throws Exception{
Socket socket = new Socket("localhost",8000);
OutputStream out=socket.getOutputStream();
Obj ectOutputStream oos=new Obj ectOutputStream(out);
InputStream in=socket.getInputStream();
Obj ectInputStream ois=new Obj ectInputStream(in);

//Call call=new Call("remotecall.HelloService","getTime",
new Class[]{},new Obj ect[]{});
Call call=new Call("remotecall.HelloService","echo",
new Class[]{String.class},new Obj ect[]{"Hello"});
oos.writeObject(call); // 向服务器发送Call 对象
call=(Call)ois.readObj ect(); //接收包含了方法执行结果的Call 对象
System.out.println(call.getResult());

ois.close();
oos.close();
socket.close();
}

public static void main(String args[])throws Exception {

new SimpleClient().invoke();
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值