ICE实现服务器客户端
本文将结合实际项目,做一个基于ice的实际项目实例应用,该实例完成客户端调用服务端接口完成消息发送,计算的功能。
1,创建java项目ICEServer,导入ice.jar.
2,在项目下创建slice文件夹,编写model.ice,service.ice,service2.ice文件,其内容如下
model.ice
#ifndef _MODEL
#define _MODEL
module com
{
module alan
{
module generated
{
module model
{
/**定义整型数组**/
sequence<int> IntegerArray;
/**自定义Map类型**/
dictionary<string, string> CustomMap;
/**消息类型**/
enum MessageType {ERROR,INFO,WARNING};
/**计算操作类型**/
enum CalcType {Adds,Subtract,Multiply,Divide};
/**消息的操作类型**/
enum ActionType {Add,Remove,Stop,Start,Pause};
/** 消息结构 **/
["java:getset"]
struct Message {
/**消息类型**/
MessageType type;
/**消息类型**/
ActionType action;
/**相关id**/
IntegerArray relatedIds;
/**扩展属性**/
CustomMap extention;
};
};
};
};
};
#endif
service.ice
#ifndef _GENERATED
#define _GENERATED
#include <model.ice>
module com
{
module alan
{
module generated
{
interface MessageServiceIce
{
/**
* 向ice服务发送信息
* @param message 消息内容
* @return true 成功 false 失败
*/
string sendMessage(model::Message msg);
};
};
};
};
#endif
service2.ice
#ifndef _GENERATED
#define _GENERATED
#include <model.ice>
module com
{
module alan
{
module generated
{
interface CalcServiceIce
{
/**
* 服务端计算方法
* @param d1 计算数1
* @param d2 计算数2
* @param type 计算方式
* @return true 成功 false 失败
*/
double calc(double d1, double d2, model::CalcType cal);
};
};
};
};
#endif
3.dos环境下执行
cd E:\workspace\ICEService\slice
E:\Ice-3.3.0\bin\slice2java -I. --output-dir=../src *.ice //生产代码
E:\Ice-3.3.0\bin\slice2html -I. --output-dir=doc *.ice//生产doc文档,可以忽略
将生产generated包下代码以jar包方式导出icetest.jar,并在项目中建立lib目录放入其中(把ice.jar也放入lib下,以备后用),可以删除其生产代码,以jar方式调用其代码。
4,编写发布接口实现代码和服务器端代码
CalcServiceIceImpl .java实现数学计算:
public class CalcServiceIceImpl extends _CalcServiceIceDisp {
public double calc(double num1, double num2, CalcType type,
Current arg3) {
double re = 0.0d;
switch (type) {
case Adds:
re = num1 + num2;
break;
case Subtract:
re = num1 - num2;
break;
case Multiply:
re = num1 * num2;
break;
case Divide:
re = num1 / num2;
break;
default:
break;
}
return re;
}
}
MessageServiceIceImpl .java实现发送消息
public class MessageServiceIceImpl extends _MessageServiceIceDisp {
public String sendMessage(Message msg, Current __current) {
String str = msg.getType() +" "+ msg.getAction()+" " + Arrays.toString(msg.getRelatedIds());
return str;
}
}
IceService .java实现服务器端接口注册:
public class IceService {
public static void main(String[] args){
int status = 0;
Communicator ic = null;
try{
ic = Ice.Util.initialize(args);
Ice.ObjectAdapter adapter = ic.createObjectAdapterWithEndpoints("testAdapter", "default -h *");
ObjectImpl object1 = new MessageServiceIceImpl();
ObjectImpl object2 = new CalcServiceIceImpl();
adapter.add(object1, ic.stringToIdentity("messageService"));
adapter.add(object2, ic.stringToIdentity("calcService"));
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);
}
}
5,发布接口
在项目下创建deploy文件夹,在其下创建config-ice.grid配置文件
IceGrid.InstanceName=IceTestServiceGrid
#
# The IceGrid locator proxy.
#
Ice.Default.Locator=IceTestServiceGrid/Locator:tcp -p 10000
#
# IceGrid registry configuration.
#
IceGrid.Registry.Client.Endpoints=tcp -p 10000
IceGrid.Registry.Server.Endpoints=tcp
IceGrid.Registry.Internal.Endpoints=tcp
IceGrid.Registry.Data=db/rescenter_registry
IceGrid.Registry.PermissionsVerifier=IceTestServiceGrid/NullPermissionsVerifier
IceGrid.Registry.AdminPermissionsVerifier=IceTestServiceGrid/NullPermissionsVerifier
IceGrid.Registry.SSLPermissionsVerifier=IceTestServiceGrid/NullSSLPermissionsVerifier
IceGrid.Registry.AdminSSLPermissionsVerifier=IceTestServiceGrid/NullSSLPermissionsVerifier
#
# Dummy username and password for icegridadmin.
#
IceGridAdmin.Username=foo
IceGridAdmin.Password=bar
#set server active Connection Managerment
Ice.ACM.Server=60
#
# IceGrid node configuration.
#
IceGrid.Node.Name=node1
IceGrid.Node.Endpoints=tcp
IceGrid.Node.Data=db/node1
IceGrid.Node.CollocateRegistry=1
IceGrid.Node.Trace.Activator=1
IceGrid.Node.Trace.Adapter=2
IceGrid.Node.Trace.Server=3
根据需要在当前目录下创建db/node1,db/rescenter_registry文件夹
创建application.xml文件
<icegrid>
<application name="icetest">
<server-template id="icetest-server-template">
<parameter name="index" />
<server id="rescenter_${index}" exe="C:\Program Files\Java\jdk1.6.0_10\bin\java" activation="on-demand">
<!---server -Xms128m -Xmx256m -d64 -XX:PermSize=128m-->
<option>-classpath</option>
<option>E:\workspace\ICEServer\bin</option>
<option>-Djava.ext.dirs=E:\workspace\ICEServer\lib</option>
<option>-server</option>
<option>com.alan.ice.IceService</option>
<adapter name="testAdapter" endpoints="tcp" replica-group="ReplicatedTestAdapter" />
<property name="Ice.ThreadPool.Server.SizeMax" value="3000" />
</server>
</server-template>
<replica-group id="ReplicatedTestAdapter">
<load-balancing type="adaptive" load-sample="1" n-replicas="1" />
<object identity="messageService" type="::com::alan::ice::MessageServiceIceImpl" />
<object identity="calcService" type="::com::alan::ice::CalcServiceIceImpl" />
</replica-group>
<node name="node1">
<server-instance template="icetest-server-template" index="1" />
</node>
</application>
</icegrid>
创建start_server.bat
path=%path%;E:\Ice-3.3.0\bin
icegridnode --Ice.Config=config-ice.grid --deploy application.xml
pause
创建完成后就可以双击start_server.bat来启动服务了
6,创建客户端调用项目ICEClient,导入ice.jar以及前面生产的icetest.jar,在项目下创建IceClient .java
public class IceClient {
public static void main(String[] args){
int status = 0;
Communicator ic = null;
try{
String str = String.format("%s:%s -h %s -p %s", "IceTestServiceGrid/Locator","tcp" ,"localhost", "10000");
InitializationData localInitializationData = new InitializationData();
localInitializationData.properties = Util.createProperties();
localInitializationData.properties.setProperty("Ice.Default.Locator", str);
ic = Util.initialize(localInitializationData);
MessageServiceIcePrx messageclient = MessageServiceIcePrxHelper.checkedCast(ic.stringToProxy("messageService"));
CalcServiceIcePrx calcclient = CalcServiceIcePrxHelper.checkedCast(ic.stringToProxy("calcService"));
if (messageclient == null || calcclient == null )
throw new Error("Invalid proxy");
Map<String ,String > map = new HashMap<String, String>();
Message msg = new Message(MessageType.INFO, ActionType.Add,new int[]{1},map);
System.out.println(messageclient.sendMessage(msg));//调用接口完成消息发送
System.out.println(calcclient.calc(12, 4, CalcType.Adds));//调用接口完成数学计算
} 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);
}
}
7,执行IceClient ,控制台输出
INFO Add [1]
ICE实现服务器客户端的更多相关文章
- 安卓DJ113舞曲网应用客户端 项目源码(服务器+客户端)
Android DJ113舞曲网app客户端 播放器源码 项目源码(服务器+客户端),这个项目整体有点类似天天动听的效果,非常漂亮的,支持第三方登录等功能,非常完整的一个音乐项目. 源码下载:htt ...
- C#中国象棋+游戏大厅 服务器 + 客户端源码
来源:www.ajerp.com/bbs C#中国象棋+游戏大厅 服务器 + 客户端源码 源码开源 C#版中国象棋(附游戏大厅) 基于前人大虾的修改版 主要用委托实现 服务器支持在线人数,大厅桌数的设 ...
- 运用socket实现简单的服务器客户端交互
Socket解释: 网络上的两个程序通过一个双向的通信连接实现数据的交换,这个连接的一端称为一个socket. Socket的英文原义是“孔”或“插座”.作为BSD UNIX的进程通信机制,取后一种意 ...
- CentOS_6.5 64位系统,安装git服务器+客户端
================ git服务器安装 ==================== CentOS安装Git服务器 Centos 6.4 + Git 1.8.2.2 + gitosis## . ...
- nginx配置SSL实现服务器/客户端双向认证
http://blog.csdn.net/kunoy/article/details/8239653 本人不才,配置了两天,终于搞出来了,结合网上诸多博文,特此总结一下! 配置环境: Ubuntu 1 ...
- Java新AIO/NIO2:AsynchronousServerSocketChannel和AsynchronousSocketChannel简单服务器-客户端
Java新AIO/NIO2:AsynchronousServerSocketChannel和AsynchronousSocketChannel简单服务器-客户端用AsynchronousServerS ...
- c++下基于windows socket的单线程服务器客户端程序(基于TCP协议)
今天自己编写了一个简单的c++服务器客户端程序,注释较详细,在此做个笔记. windows下socket编程的主要流程可概括如下:初始化ws2_32.dll动态库-->创建套接字-->绑定 ...
- c++下基于windows socket的服务器客户端程序(基于UDP协议)
前天写了一个基于tcp协议的服务器客户端程序,今天写了一个基于UDP协议的,由于在上一篇使用TCP协议的服务器中注释已经较为详细,且许多api的调用是相同的,故不再另外注释. 使用UDP协议需要注意几 ...
- kaldi - Online Audio Server(服务器客户端建立方法-旧版在线解码)
目录 一.服务器客户端识别系统建立方法 1. Command line to start the server(服务器端启动方式): 2. Command line to start the clie ...
随机推荐
- Flutter中集成Font Awesome
1.添加引用 在 pubspec.yaml文件中,加入 font awesome的引用 dependencies: flutter: sdk: flutter # The following adds ...
- 转:java 重定向和转发的区别
response.sendredirect("http://www.foo.com/path/error.html"); 重定向和转发有一个重要的不同:当使用转发时,JSP容器将使 ...
- RabbitMQ入门(2)——工作队列
前面介绍了队列接收和发送消息,这篇将学习如何创建一个工作队列来处理在多个消费者之间分配耗时的任务.工作队列(work queue),又称任务队列(task queue). 工作队列的目的是为了避免立刻 ...
- nginx web服务器详解1(转)
原创作品,允许转载,转载时请务必以超链接形式标明文章 原始出处 .作者信息和本声明.否则将追究法律责任.http://freeloda.blog.51cto.com/2033581/1285332 大 ...
- Python基础笔记系列十:模块
本系列教程供个人学习笔记使用,如果您要浏览可能需要其它编程语言基础(如C语言),why?因为我写得烂啊,只有我自己看得懂!! 模块 #1.类比于java中的jar包,模块能让你能够有逻辑地组织你的Py ...
- Vuejs methods how to use
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8&qu ...
- 分布式系统中的幂等性-zookeeper与dubbo
现如今我们的系统大多拆分为分布式SOA,或者微服务,一套系统中包含了多个子系统服务,而一个子系统服务往往会去调用另一个服务,而服务调用服务无非就是使用RPC通信或者restful,既然是通信,那么就有 ...
- Java循环结构 - for, while 及 do...while
Java循环结构 - for, while 及 do...while 顺序结构的程序语句只能被执行一次.如果您想要同样的操作执行多次,,就需要使用循环结构. Java中有三种主要的循环结构: whil ...
- 在.net中运用HTMLParser解析网页的原理和方法
本文介绍了.net 版的一个HTMLParser网页解析开源类库(Winista.HTMLParser)的功能特性.工作原理和使用方法.对于使用.net进行Web信息提取的开发人员进行了一次HTMLP ...
- raid write back / write throught
RAID write back指的是raid控制器能够将写入的数据写入自己的缓存中,并把它们安排到后续再执行,这样做的好处就是不需要等实际写入磁盘再返回,因此写入更快.对于数据库而言,这一点更为重要, ...