[z]protobuf实现c++与java之间的数据传递,beancopy数据到前台
[z]http://blog.csdn.net/xhyzdai/article/details/46684335
定义proto文件
- option java_package = "com.wy.web";
- message my_message{
- required string startedTime =1;
- required string version=2;
- required double configuredCapacity=3;
- required double dfsUsed =4;
- required int32 fileNum=5;
- required int32 replicatedFilesNum =6;
- required int32 blockNum =7;
- required int32 livedNodeNum =8;
- required int32 decommissioningNodeNum=9;
- }
生成proto文件对应的类
windows:
protoc.exe --java_out=.\ infor.proto(注意'\'和文件名之间有空格,c++命令为protoc.exe --java_out==.\ infor.proto)
protoc -I=./ --java_out=./ infor.proto
c++代码,向java端发送数据
- #include <netinet/in.h> // for sockaddr_in
- #include <sys/types.h> // for socket
- #include <sys/socket.h> // for socket
- #include <unistd.h>
- #include <stdio.h> // for printf
- #include <stdlib.h> // for exit
- #include <string.h> // for bzero
- #include <string>
- #include <google/protobuf/message_lite.h>
- #include <google/protobuf/io/coded_stream.h>
- #include <google/protobuf/io/zero_copy_stream_impl_lite.h>
- #include "infor.pb.h"
- #define HELLO_WORLD_SERVER_PORT 8000
- #define LENGTH_OF_LISTEN_QUEUE 20
- #define BUFFER_SIZE 1024
- #define FILE_NAME_MAX_SIZE 512
- int main()
- {
- std::string time = "2015-06-25";
- std::string version = "0.0.1";
- double config = 2.0;
- double dfs = 3.0;
- int file = 1000;
- int rep = 1000;
- int block = 1000;
- int live = 1000;
- int de = 1000;
- struct sockaddr_in server_addr;
- bzero(&server_addr,sizeof(server_addr));
- server_addr.sin_family = AF_INET;
- server_addr.sin_addr.s_addr = htons(INADDR_ANY);
- server_addr.sin_port = htons(HELLO_WORLD_SERVER_PORT);
- int server_socket = socket(PF_INET,SOCK_STREAM,0);
- if( server_socket < 0)
- {
- printf("Create Socket Failed!");
- exit(1);
- }
- int opt =1;
- setsockopt(server_socket,SOL_SOCKET,SO_REUSEADDR,&opt,sizeof(opt));
- if( bind(server_socket,(struct sockaddr*)&server_addr,sizeof(server_addr)))
- {
- printf("Server Bind Port : %d Failed!", HELLO_WORLD_SERVER_PORT);
- exit(1);
- }
- if ( listen(server_socket, LENGTH_OF_LISTEN_QUEUE) )
- {
- printf("Server Listen Failed!");
- exit(1);
- }
- while (1)
- {
- struct sockaddr_in client_addr;
- socklen_t length = sizeof(client_addr);
- int new_server_socket = accept(server_socket,(struct sockaddr*)&client_addr,&length);
- if ( new_server_socket < 0)
- {
- printf("Server Accept Failed!\n");
- break;
- }
- my_message mm;
- mm.set_startedtime(time);
- mm.set_version(version);
- mm.set_configuredcapacity(config);
- mm.set_dfsused(dfs);
- mm.set_filenum(file);
- mm.set_replicatedfilesnum(rep);
- mm.set_blocknum(block);
- mm.set_livednodenum(live);
- mm.set_decommissioningnodenum(de);
- file += 1; rep += 1; block += 1; live += 1; de += 1;
- int len = mm.ByteSize() + 4;
- char *buffer = new char[len];
- google::protobuf::io::ArrayOutputStream arrayOut(buffer, len);
- google::protobuf::io::CodedOutputStream codedOut(&arrayOut);
- codedOut.WriteVarint32(mm.ByteSize());
- //write protobuf ack to buffer
- mm.SerializeToCodedStream(&codedOut);
- //mm.SerializeToArray(buffer, len);
- if(send(new_server_socket,buffer,len,0)<0)
- {
- printf("Send File:\t%s Failed\n", "ddddd");
- break;
- }
- close(new_server_socket);
- delete buffer;
- }
- close(server_socket);
- return 0;
- }
java接收线程,通过beancopy更新到数据中心
- package com.wy.web;
- import java.io.InputStream;
- import java.net.Socket;
- import java.net.UnknownHostException;
- import com.wy.util.BeanUtil;
- import com.wy.web.Infor.my_message;
- /**
- * 数据监听线程,从服务器端取得数据并更新到数据中心
- */
- public class dataListennerT extends Thread{
- private Socket socket;
- private DataCenter dataCenter;
- private static final String host="10.9.3.45";
- //private static final String host="10.9.3.165";
- public dataListennerT(DataCenter dataCenter) {
- this.dataCenter=dataCenter;
- }
- @Override
- public void run() {
- while(true)
- {
- try {
- Thread.sleep(1000);
- } catch (InterruptedException e1) {
- // TODO Auto-generated catch block
- e1.printStackTrace();
- }
- try {
- socket = new Socket(host,8000);
- System.out.println("成功连接");
- read(socket);
- } catch (UnknownHostException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (Exception e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- }
- private void read(Socket socket) {
- InputStream clientIs;
- try {
- clientIs = socket.getInputStream();
- //Infor.my_message ms = Infor.my_message.parseDelimitedFrom(clientIs);
- /*-------------------------------*/
- byte[] arr = new byte[256];
- int len = clientIs.read(arr);
- byte[] data=new byte[len];
- for(int i=0;i<len;i++)
- data[i]=arr[i];
- Infor.my_message ms = Infor.my_message.parseFrom(data);
- System.out.println(ms.getStartedTime());
- //updataCenter(ms);
- BeanUtil.beanFieldCopy(ms, dataCenter, "Csi",true);
- } catch (Exception e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
数据中心
- package com.wy.web;
- import org.primefaces.push.annotation.Singleton;
- /**
- * 数据中心,从服务器取所有前台需要的数据
- */
- public class DataCenter {
- private static DataCenter instance;
- private String csiStartedTime = "20150624";
- private String csiVersion = "1.0.0";
- private double csiConfiguredCapacity = 1;
- private double csiDfsUsed = 1024;
- private int csiFileNum = 26;
- private int csiReplicatedFilesNum = 100;
- private int csiBlockNum;
- private int csiLivedNodeNum = 3;
- private int csiDecommissioningNodeNum = 0;
- public String getCsiStartedTime() {
- return csiStartedTime;
- }
- public void setCsiStartedTime(String csiStartedTime) {
- this.csiStartedTime = csiStartedTime;
- }
- public String getCsiVersion() {
- return csiVersion;
- }
- public void setCsiVersion(String csiVersion) {
- this.csiVersion = csiVersion;
- }
- public double getCsiConfiguredCapacity() {
- return csiConfiguredCapacity;
- }
- public void setCsiConfiguredCapacity(double csiConfiguredCapacity) {
- this.csiConfiguredCapacity = csiConfiguredCapacity;
- }
- public double getCsiDfsUsed() {
- return csiDfsUsed;
- }
- public void setCsiDfsUsed(double csiDfsUsed) {
- this.csiDfsUsed = csiDfsUsed;
- }
- public int getCsiFileNum() {
- return csiFileNum;
- }
- public void setCsiFileNum(int csiFileNum) {
- this.csiFileNum = csiFileNum;
- }
- public int getCsiReplicatedFilesNum() {
- return csiReplicatedFilesNum;
- }
- public void setCsiReplicatedFilesNum(int csiReplicatedFilesNum) {
- this.csiReplicatedFilesNum = csiReplicatedFilesNum;
- }
- public int getCsiLivedNodeNum() {
- return csiLivedNodeNum;
- }
- public void setCsiLivedNodeNum(int csiLivedNodeNum) {
- this.csiLivedNodeNum = csiLivedNodeNum;
- }
- public int getCsiDecommissioningNodeNum() {
- return csiDecommissioningNodeNum;
- }
- public void setCsiDecommissioningNodeNum(int csiDecommissioningNodeNum) {
- this.csiDecommissioningNodeNum = csiDecommissioningNodeNum;
- }
- public int getCsiBlockNum() {
- return csiBlockNum;
- }
- public void setCsiBlockNum(int blockNum) {
- this.csiBlockNum = blockNum;
- }
- public static DataCenter getClient() {
- if (instance == null) {
- synchronized (Singleton.class) {
- if (instance == null) {
- instance = new DataCenter();
- }
- }
- }
- return instance;
- }
- private DataCenter() {
- //System.out.println("DataCenter!!!==========");
- new dataListennerT(this).start();
- }
- }
bean copy,实现将两个类属性复制
- package com.wy.util;
- import java.lang.reflect.Field;
- import java.lang.reflect.Method;
- import java.util.HashSet;
- public class BeanUtil {
- public BeanUtil() {
- }
- public static synchronized void beanFieldCopy(Object src, Object des, String prefix,boolean desPrefix) {
- Class srcClass = src.getClass();
- Class desClass = des.getClass();
- HashSet<String> setFields = new HashSet<String>();
- Method[] srcMethods = srcClass.getMethods();
- Method[] desMethods = desClass.getMethods();
- //System.out.println(desClass.getName());
- // 保存提供set方法的参数
- for (int i = 0; i < desMethods.length; i++) {
- Method desMethod = desMethods[i];
- String desMethodName = desMethod.getName();
- if (desMethodName.startsWith("set"))
- {
- if(desPrefix)
- setFields.add(desMethodName.substring(3 + prefix.length(),
- desMethodName.length()));
- else
- setFields.add(desMethodName.substring(3,
- desMethodName.length()));
- }
- }
- // if(desClass.getName().equals("com.wy.web.ClusterSummaryInfo"))
- // System.out.println(setFields);
- // Field[] desFields = desClass.getDeclaredFields();
- for (int i = 0; i < srcMethods.length; i++) {
- Method method = srcMethods[i];
- String srcMethodName = method.getName();
- if (srcMethodName.startsWith("get")) {
- String fieldName;
- if(desPrefix)
- fieldName = srcMethodName.substring(3, srcMethodName.length());
- else
- fieldName=srcMethodName.substring(3+prefix.length(), srcMethodName.length());
- // if(desClass.getName().equals("com.wy.web.ClusterSummaryInfo"))
- // System.out.println(fieldName);
- if (setFields.contains(fieldName)) {
- String invokeMethodName;
- if(desPrefix)
- invokeMethodName= "set" + prefix + fieldName;
- else
- invokeMethodName="set"+fieldName;
- //System.out.println(desClass.getName()+" "+invokeMethodName);
- try {
- Method invokeMethod = desClass.getMethod(
- invokeMethodName,
- new Class[] { method.getReturnType() });
- Object result = method.invoke(src, new Object[] {});
- if (result == null)
- break;
- invokeMethod.invoke(des, new Object[] { result });
- } catch (Exception e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- }
- }
- }
- }
[z]protobuf实现c++与java之间的数据传递,beancopy数据到前台的更多相关文章
- Activity之间使用intent传递大量数据带来问题总结
转载:大飞 http://blog.csdn.net/rflyee/article/details/47441405 Activity之间使用Parcel传递大量数据产生的问题. Activity ...
- Activity之间的数据传递
最常用的Activity之间的数据传递. btnStartAty1.setOnClickListener(new View.OnClickListener() { @Override public v ...
- ASP.NET MVC 之控制器与视图之间的数据传递
今天,我们来谈谈控制器与视图之间的数据传递. 数据传递,指的是视图与控制器之间的交互,包括两个方向上的数据交互,一个是把控制器的数据传到视图中,在视图中如何显示数据,一个是把视图数据传递到控制器中, ...
- 序列化之protobuf与avro对比(Java)
最近在做socket通信中用到了关于序列化工具选型的问题,在调研过程中开始趋向于用protobuf,可以省去了编解码的过程.能够实现快速开发,且只需要维护一份协议文件即可. 但是调研过程中发现了pro ...
- C#和java之间的一些差异与共性
C#与java之间的一些共性和差异整理 隐藏:与java中的重写几乎一致,但是需要添加new关键字让编译器知道,否则会有警告 虚方法:1.声明为virtual的方法就是虚方法,在子类中使用overri ...
- scala与java之间的那些事
scala与java之间的关系,我认为可以用一句话来开头:scala来源于java,但又高于java. scala的设计者Martin Odersky就是一个JAVA控,这位牛人设计了javac和编写 ...
- Linux 环境下思源黑体字体与 Java 之间的兼容性问题的解决(补充说明)
在前一篇随笔中,我讲了一下有关 Linux 环境下思源黑体与 Java 之间的兼容性问题,后来经过测试发现,默认安装的思源黑体字体同时包含简体字体和繁体字体,并且其对应的语言编码也是不同的.尝试着把繁 ...
- mysql/sql server和java之间的数据类型对应关系
Mysql************************************当前列 ClassName ColumnType DisplaySize TypeName0: java.lang.I ...
- Eclipse中java向数据库中添加数据,更新数据,删除数据
前面详细写过如何连接数据库的具体操作,下面介绍向数据库中添加数据. 注意事项:如果参考下面代码,需要 改包名,数据库名,数据库账号,密码,和数据表(数据表里面的信息) package com.ning ...
随机推荐
- [Shell]Bash基本功能:历史命令 & 别名 & Bash快捷键
/*----------------------------------------------------------------------------------------------- @黑 ...
- 12.JDBC-mysql.md
目录 API简述 Driver接口: 表示java驱动程序接口.所有的具体的数据库厂商要来实现此接口. DriverManager类: 驱动管理器类,用于管理所有注册的驱动程序 Connection接 ...
- iOS中的MVC
我们今天谈谈cocoa程序设计中的 模型-视图-控制器(MVC)范型.我们将从两大方面来讨论MVC: 什么是MVC? M.V.C之间的交流方式是什么样子的? 理解了MVC的概念,对cocoa程序开 ...
- MATLAB总结二
1.如何将一个多项式中的系数按照幂次提取出来? sym2poly(ans) %ans为一个多项式. 2.在写第二份模式识别的大作业时遇到如下困难: 每个样本贡献给总概率的是一个关于x的表达式,我将所有 ...
- JAVA语言 第七周
啊因为来学校了,没有网,昨天的总结今天来写吧. num1=In.next(); student1[number].stuNum=num1; 这个添加的代码,显示添加成功了,但是根本查询不出来,烦 ...
- linux下网络配置
配置相关 http://bbs.acehat.com/thread-813-1-1.html
- io输出流变为输入流
java 输出流转化为输入流 new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
- ARM9/ARM11/Cortex A8处理器(转载) .
//toppic:推荐几个值得中小企业使用的ARM9/ARM11/Cortex A8处理器 // 作者:gooogleman //原文地址:http://blog.csdn.net/goooglema ...
- 七个不可错过的React组件库与开发框架
React是如今最火爆的前端技术,而React最棒的一个特点就是有大量功能丰富的组件库和开发框架可用.从按钮到卷轴到工具条,应有尽有,而且这些组件可以各行其是,也可以组装成复杂的UI,你也可以把UI分 ...
- svn 更新lib库时,报错
svn: E195012: Unable to find repository location for svn:// in revision 9718 Can't revert without re ...