zeroC的Ice开发过程,进行了简单的学习,对构架的就不介绍的,分布式的,开发hello的过程如下:
1、按 slice 格式建立一个文本文件(hello.ice),本例的内容如下:
module dice{
interface Hello{
string say(string s);
};
};
//slice2java --output-dir demo hello.ice
2、运行 ice 的bin 目录下的 slice2java 程序,假设生成的代码放在 demo 目录下,在 dos 下输入:
slice2java --output-dir demo hello.ice
如不能运行,请设置好 path 到 ice 的bin 目录.
3.将 demo 目录下的 dice 目录copy到你的java项目源代码目录,建立一个 HelloI 的类(类命名方式:interface名+I)
内容如下:
package dice.mp;
import dice.*;
import Ice.*;
import java.util.*;
public class HelloI extends _HelloDisp {
public HelloI(){
System.out.println("cons:"+this);
}
public String say(String s, Ice.Current __current){
return "Hello "+s+",Time is "+new Date();
}
}
4.建立 server 和 client 文件。
server内容如下:
package dice.mp;
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("HellorAdapter", "default -p 10000");
Ice.Object object = new HelloI();
adapter.add(object,ic.stringToIdentity("Hello"));
adapter.activate();
ic.waitForShutdown();
} catch (Ice.LocalException e) {
e.printStackTrace();
status = 1;
} catch (Exception e) {
System.err.println(e.getMessage());
status = 1;
}
if (ic != null) {
try {
ic.destroy();
} catch (Exception e) {
System.err.println(e.getMessage());
status = 1;
}
}
System.exit(status);
}
}
client 内容如下:
package dice.mp;
import dice.*;
import Ice.ObjectPrx;
import Ice.Util;
import Ice.Communicator;
public class Client {
public static void main(String[] args) throws Exception {
Communicator ic = null;
try {
ic = Util.initialize(args);
//Ice.ObjectPrx base = ic.stringToProxy("Hello:default -p 10000");
ObjectPrx base = ic.stringToProxy("Hello:tcp -h 127.0.0.1 -p 10000");
HelloPrx hello = HelloPrxHelper.checkedCast(base);
if (hello == null) throw new Error("Invalid proxy");
String msg=hello.say("机器人");
System.out.println(msg);
} catch (Ice.LocalException e) {
e.printStackTrace();
} catch (Exception e) {
System.err.println(e.getMessage());
}
if (ic != null) {
try {
ic.destroy();
System.out.println("通讯器关闭");
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
}
}
5、运行、测试
注意要把ice 的 Ice.jar 设置到类路径中。
先运行 Server , 再运行 client .
到此,ok, 基本够用。