Burlap中hessian协议研究-自定义远程协议实现(十一)远程服务注册类实现

服务端调用相关的代码将结果发送到客户端

package cn.com.huawei.socket.remote.rpc;

import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

/**
 * 远程服务的服务端
 *
 * @author bailonggang 2009-2-21 下午05:48:58
 */
public class RemoteServerProxyFactory {
 private int port;

 public RemoteServerProxyFactory(int port) {
  this.port = port;
 }
    //使用缓存存放远程服务对象的
 private Map<String, Object> remoteObjects = new HashMap<String, Object>();

 /**
  *
  * @param className
  * @param remoteObject
  */
 public void register(String className, Object remoteObject) {
  this.remoteObjects.put(className, remoteObject);
 }

 /**
  *
  * @throws Exception
  */
 public void service() throws Exception {
  ServerSocket serversocket = new ServerSocket(port);
  System.out.println("服务器启动.....");
  while (true) {
   Socket socket = serversocket.accept();
   InputStream is = socket.getInputStream();
   OutputStream os = socket.getOutputStream();
   ObjectInputStream ois = new ObjectInputStream(is);
   ObjectOutputStream oos = new ObjectOutputStream(os);
   Call call = (Call) ois.readObject();
   System.out.println(call);
   call = invokeCall(call);
   oos.writeObject(call);
   ois.close();
   oos.close();
   socket.close();
  }
 }

 /**
  * 调用相关的远程方法应用
  * @param call
  * @return
  */
 public Call invokeCall(Call call) {
  Object result = null;
  try {
   String className = call.getClassName();
   String methodName = call.getMethodName();
   Object[] params = call.getParams();
   Class[] paramTypes = call.getParamTypes();
   Class target = Class.forName(className);
   Method method = target.getMethod(methodName, paramTypes);
   Object remoteObject = this.remoteObjects.get(className);
   if (remoteObject == null) {
    throw new Exception("ClassName " + className + " 的远程对象不存在!!");
   } else {
    result = method.invoke(remoteObject, params);
   }
  } catch (Exception e) {
   result = e;
  }
  // 设置方法运行的结果
  call.setResult(result);
  return call;
 }

}

你可能感兴趣的:(java,应用服务器,socket,OS,远程访问技术的研究)