Ice客户端的同步及AMI异步模式-JAVA

 

废话不多说,最简单的源码比较一下是最快的方法.

1、slice文件 Demo.ice

#ifndef HELLO_ICE
#define HELLO_ICE

module Demo {  
    interface Printer {  
        ["ami"] string printString(string s);   //["ami"] 头表示此方法是异步的,客户端无需等待立即返回;
    };  
};

#endif

 

2、slice2java 生成骨架代码

 

3、接口实现:PrinterI.java

import Ice.*;
import Demo.*;


public class PrinterI extends _PrinterDisp{  

 public String printString(String s, Current __current) {  
  // TODO Auto-generated method stub  
  StringBuilder sb=new StringBuilder(s);  
  s = sb.reverse().toString();   //反转字符串
  return s;  
 }
}

4、异步回调实现:APP.java

import Demo.*;

public class APP extends AMI_Printer_printString
{
 public void ice_response(String __ret){
  System.out.println("printString完成~"+__ret);
 }

 public void ice_exception(Ice.LocalException ex){
  System.out.println(ex.toString()+"出错啦~");
 }
}

5、服务端 Server.java

public class Server {  
 public static void main(String[] args) {  
  int status = 0;  
  Ice.Communicator ic = null;  
  try {  
   ic = Ice.Util.initialize(args);// 初始化参数
   Ice.ObjectAdapter adapter = ic.createObjectAdapterWithEndpoints("simplePrinterAdapter", "default -h 10.147.6.85 -p 10000");// 创造对象适配器  
   Ice.Object objcet = new PrinterI();// 创建servant对象
   adapter.add(objcet, Ice.Util.stringToIdentity("simplePrinter"));// 适配器添加一个新的servant,给servant对象取个名字  
   adapter.activate();
   System.out.println("connection success");  
   ic.waitForShutdown();
  } catch (Ice.LocalException e) {  
            e.printStackTrace();  
             status = 1;  
     } catch (Exception e) {  
             System.err.print(e.getMessage());  
             status = 1;  
     } finally {  
            if (ic != null) {  
                 ic.destroy();  
            }  
     }  
         System.exit(status);  
 }  
}  

 

6、客户端:Client.java


import java.util.*;
import Demo.*;

public class Client {  
 /** 
 * @param args 
 */ 
 public static void main(String[] args) {  
  int status = 0;  
  Ice.Communicator ic = null;  
  try {  
   ic = Ice.Util.initialize(args);  
   Ice.ObjectPrx base = ic.stringToProxy("simplePrinter:default -h 10.147.6.85 -p 10000" + "");  
   PrinterPrx printer = PrinterPrxHelper.checkedCast(base);  
   if (printer == null) {  
    System.out.println("invalid proxy");
   }  
   String out = printer.printString("I love you");//同步调用
   System.out.println(out);
   //printer.printString_async(new APP(), "Hello World!");//异步调用,基本上总是在下面的打印输出'做点其他事情~'后输出
   System.out.println("做点其他事情~");

   //Scanner input = new Scanner(System.in);
   //String str = input.next();

  } catch (Ice.LocalException e) {  
   // TODO: handle exception  
   e.printStackTrace();  
   status = 1;  
  } catch (Exception e) {
   System.err.print(e.getMessage());  
   status = 1;  
  } finally {  
   if (ic != null) {  
    ic.destroy();  
   }
  }
  System.exit(status);  
 }  
 
}

你可能感兴趣的:(java,ice)