zeroc ice开发环境搭建上篇文章https://it.baiked.com/zerocice/260.html,我先下来写个简单的server/client之间调用
1,我们建立一个java工程:ice_hello
2,建立slice文件夹,滨海再其目录下建立:Hello.ice,内容如下:
[["java:package:com.xub.service"]] // 定义java包名
module demo
{
interface Hello
{
string sayHello(string s);
};
};
右单击工程ice_hello->Ice Builder->Add Ice Builder ,如果没有错误将会自动生成generated文件夹及内容,如下图所示:
下来,我们写一个服务接口实现类,代码如下:
package com.xub.service.demo.impl;package com.xub.service.demo.impl;
import com.xub.service.demo._HelloDisp;
import Ice.Current;
public class HelloI extends _HelloDisp {
@Override
public String sayHello(String s, Current __current) {
// TODO Auto-generated method stub
return "Hello"+s;
}
}
写一个服务启动类,代码如下:
package com.xub.service.demo.server;
import com.xub.service.demo.impl.HelloI;
public class Server {
public static void main(String[] args) {
int status = 0;
Ice.Communicator ic = null;
try{
System.out.println("Server starting...");
ic = Ice.Util.initialize(args);
Ice.ObjectAdapter adapter = ic.createObjectAdapterWithEndpoints("HelloAdapter", "default -p 10000");
Ice.Object object = new HelloI();
adapter.add(object, ic.stringToIdentity("hello"));
adapter.activate();
System.out.println("Server start success.");
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);
}
}
写一个客户端类,代码如下:
package com.xub.service.demo.client;
import com.xub.service.demo.HelloPrx;
import com.xub.service.demo.HelloPrxHelper;
public class Client {
public static void main(String[] args) {
int status = 0;
Ice.Communicator ic = null;
try{
ic = Ice.Util.initialize(args);
Ice.ObjectPrx base = ic.stringToProxy("hello:default -p 10000");
HelloPrx hello = HelloPrxHelper.checkedCast(base);
if(hello == null){
throw new Error("Invalid proxy");
}
String s = hello.sayHello("World!");
System.out.println(">>"+s);
}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);
}
}
测试一下
先启动Server类-->再启动Client类-->控制台输出:Hello World!
注
也可以用命令生成,如下图,生成代码就在同级目录下: