hello.ice #ifndef simple_ice#define simple_ice//名字空间 or 包名module demo.slice.hello{ interface hello{ void printstring(string s); };};
#endif
服务器: helloi.java
package demo.ice.hello.server;
import demo.slice.hello._hellodisp;import ice.current;
/** * @author mudfishcn * * servant class: helloi * _hellodisp 基类由slice2java编译器生成,它是一个抽象类。 * _hellodisp 抽象类包含一个printstring()方法。 */public class helloi extends _hellodisp {
/* (non-javadoc) * @see demo._hellooperations#printstring(java.lang.string, ice.current) */ public void printstring(string s, current __current) { // todo auto-generated method stub system.out.println(s); }
}
helloserver.java
package demo.ice.hello.server;
import ice.localexception;
/** * @author mudfishcn * version: 1.0.1 */public class helloserver { public static void main(string[] args) { // 定义status变量,用来控制服务器. int status = 0; ice.communicator ic = null; //声明一个communicator 对象ic try { // 初始化ice运行时 ic = ice.util.initialize(args); /* * 创建一个对象适配器(objectadapter)对象ioadapter,并初始化之。 * 参数"helloworldadapter":表示适配器的名字。 * 参数"default -p 10000":表示适配器使用缺省协议(tcp/ip)在端口10000处监听到来的请求。 * 服务器配置完成. */ ice.objectadapter ioadapter = ic.createobjectadapterwithendpoints( "helloworldadapter", "default -p 10000");
/* * 为hello接口创建一个servant. */ ice.object iobject = (ice.object) new helloi(); /* * 将新的servant添加到适配器, * 并将这个新的servant命名为"helloworld" */ ioadapter.add(iobject, ice.util.stringtoidentity("helloworld")); /* * 激活适配器,以使服务器开始处理来自客户的请求 */ ioadapter.activate();
/* * 挂起发出调用的线程,直到服务器实现终止为止. * 或者是通过发出一个调用关闭运行时(run time)的指令来使服务器终止. */ ic.waitforshutdown(); } catch (localexception e) { // 捕捉ice运行时可能抛出的所有异常 e.printstacktrace(); status = 1; } catch (exception e) { // 捕捉串常量 e.printstacktrace(); status = 1; } finally { if (ic != null) { ic.destroy(); } } system.exit(status); }}
helloclient.java
package demo.ice.hello.client;
import ice.objectprx;import ice.util;import demo.slice.hello.helloprx;import demo.slice.hello.helloprxhelper;
/** * @author mudfishcn */public class helloclient { public static void main(string[] args) { int status = 0; string s; //创建一个通信器的对象ic ice.communicator ic = null; try { // 初始化ice运行时 ic = util.initialize(args); /* * 获取远程对象的代理 * 创建一个代理对象,并用通信器的stringtoproxy()方法初始化之。 * 参数:"helloworld:default -p 10000" * 表示: */ objectprx base = ic.stringtoproxy("helloworld:default -p 10000"); /* * 关键点 */ helloprx hello = helloprxhelper.checkedcast(base); //测试向下转换是否成功。如果不成功抛出异常信息"invalid proxy". if (hello == null) { throw new error("invalid proxy"); } //向服务器发送十条消息 for(int i=1;i<=10;i++){ s = "hello,world!"+integer.tostring(i); hello.printstring(s); } } catch (ice.localexception e) { e.printstacktrace(); status = 1; } catch (exception e) { e.printstacktrace(); status = 1; } finally { if (ic != null) { //销毁通信连接 ic.destroy(); } } system.exit(status); }}
