Java远程调用(二)实现一个简单的服务框架

http://blog.csdn.net/itleochen/article/details/11270829

自己实现一个服务框架

用java程序自己写一个简单的服务框架
通信协议:socket 
网络io:bio
线程方式:无限线程池
远程调用的透明化方案:jdk 动态代理Proxy
序列化:java本身



贴上核心代码:
一、发布服务方法
[java]  view plain  copy
  1. /** 
  2.  * 发布服务 
  3.  *  
  4.  * @param service 
  5.  *            服务实现 
  6.  * @param port 
  7.  *            服务端口 
  8.  * @throws Exception 
  9.  */  
  10. public static void export(final Object service, final int port)  
  11.         throws Exception {  
  12.     if (service == null)  
  13.         throw new IllegalArgumentException("service instance == null");  
  14.     if (port <= 0 || port > 65535)  
  15.         throw new IllegalArgumentException("Invalid port " + port);  
  16.     System.out.println("Export service " + service.getClass().getName()  
  17.             + " on port " + port);  
  18.     /* 服务端socket,最多同时处理1000个服务请求 */  
  19.     ServerSocket server = new ServerSocket(port, 1000);  
  20.     ExecutorService executor = Executors.newCachedThreadPool();  
  21.     ;  
  22.     for (;;) {  
  23.         try {  
  24.             // 监听client socket请求  
  25.             final Socket socket = server.accept();  
  26.             executor.execute(new Runnable() {  
  27.                 @Override  
  28.                 public void run() {  
  29.                     try {  
  30.                         try {  
  31.                             ObjectInputStream input = new ObjectInputStream(  
  32.                                     socket.getInputStream());  
  33.                             try {  
  34.                                 // 发布服务的方法名  
  35.                                 String methodName = input.readUTF();  
  36.                                 // 入参  
  37.                                 Class<?>[] parameterTypes = (Class<?>[]) input  
  38.                                         .readObject();  
  39.                                 Object[] arguments = (Object[]) input  
  40.                                         .readObject();  
  41.                                 ObjectOutputStream output = new ObjectOutputStream(  
  42.                                         socket.getOutputStream());  
  43.                                 try {  
  44.                                     Method method = service.getClass()  
  45.                                             .getMethod(methodName,  
  46.                                                     parameterTypes);  
  47.                                     Object result = method.invoke(service,  
  48.                                             arguments);  
  49.                                     output.writeObject(result);  
  50.                                 } catch (Throwable t) {  
  51.                                     output.writeObject(t);  
  52.                                 } finally {  
  53.                                     output.close();  
  54.                                 }  
  55.                             } finally {  
  56.                                 input.close();  
  57.                             }  
  58.                         } finally {  
  59.                             if (socket != null) {  
  60.                                 socket.close();  
  61.                             }  
  62.                         }  
  63.                     } catch (Exception e) {  
  64.                         e.printStackTrace();  
  65.                     }  
  66.                 }  
  67.             });  
  68.         } catch (Exception e) {  
  69.             e.printStackTrace();  
  70.         }  
  71.     }  
  72. }  

二、调用服务
[java]  view plain  copy
  1. /** 
  2.  * 引用服务 
  3.  *  
  4.  * @param <T> 
  5.  *            接口泛型 
  6.  * @param interfaceClass 
  7.  *            接口类型 
  8.  * @param host 
  9.  *            服务器主机名 
  10.  * @param port 
  11.  *            服务器端口 
  12.  * @return 远程服务 
  13.  * @throws Exception 
  14.  */  
  15. @SuppressWarnings("unchecked")  
  16. public static <T> T refer(final Class<T> interfaceClass, final String host,  
  17.         final int port) throws Exception {  
  18.     if (interfaceClass == null)  
  19.         throw new IllegalArgumentException("Interface class == null");  
  20.     if (!interfaceClass.isInterface())  
  21.         throw new IllegalArgumentException("The "  
  22.                 + interfaceClass.getName() + " must be interface class!");  
  23.     if (host == null || host.length() == 0)  
  24.         throw new IllegalArgumentException("Host == null!");  
  25.     if (port <= 0 || port > 65535)  
  26.         throw new IllegalArgumentException("Invalid port " + port);  
  27.     System.out.println("Get remote service " + interfaceClass.getName()  
  28.             + " from server " + host + ":" + port);  
  29.     return (T) Proxy.newProxyInstance(interfaceClass.getClassLoader(),  
  30.             new Class<?>[] { interfaceClass }, new InvocationHandler() {  
  31.                 public Object invoke(Object proxy, Method method,  
  32.                         Object[] arguments) throws Throwable {  
  33.                     // 建立socket并尝试连接,失败则抛出异常  
  34.                     // Socket socket = new Socket(host, port);  
  35.                     Socket socket = new Socket();  
  36.                     // socket.close()执行时 若数据没有发送完成则阻塞 10秒  
  37.                     socket.setSoLinger(true10);  
  38.                     socket.connect(new InetSocketAddress(host, port));  
  39.                     try {  
  40.                         // 往socket写数据  
  41.                         ObjectOutputStream output = new ObjectOutputStream(  
  42.                                 socket.getOutputStream());  
  43.                         try {  
  44.                             output.writeUTF(method.getName());  
  45.                             output.writeObject(method.getParameterTypes());  
  46.                             output.writeObject(arguments);  
  47.                             // 读出数据  
  48.                             ObjectInputStream input = new ObjectInputStream(  
  49.                                     socket.getInputStream());  
  50.                             try {  
  51.                                 Object result = input.readObject();  
  52.                                 if (result instanceof Throwable) {  
  53.                                     throw (Throwable) result;  
  54.                                 }  
  55.                                 return result;  
  56.                             } finally {  
  57.                                 input.close();  
  58.                             }  
  59.                         } finally {  
  60.                             if (output != null) {  
  61.                                 output.close();  
  62.                             }  
  63.                         }  
  64.                     } finally {  
  65.                         if (socket != null) {  
  66.                             socket.close();  
  67.                         }  
  68.                     }  
  69.                 }  
  70.             });  
  71. }  

没法传附件么?
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值