protobuf实现c++与java之间的数据传递,beancopy数据到前台

定义proto文件

 

 
  1. option java_package = "com.wy.web";

  2. message my_message{

  3. required string startedTime =1;

  4. required string version=2;

  5. required double configuredCapacity=3;

  6. required double dfsUsed =4;

  7. required int32 fileNum=5;

  8. required int32 replicatedFilesNum =6;

  9. required int32 blockNum =7;

  10. required int32 livedNodeNum =8;

  11. required int32 decommissioningNodeNum=9;

  12. }

 

生成proto文件对应的类

windows:

protoc.exe --java_out=.\ infor.proto(注意'\'和文件名之间有空格,c++命令为protoc.exe --java_out==.\ infor.proto)

linux:

protoc -I=./ --java_out=./ infor.proto

 

c++代码,向java端发送数据

 

 

 
  1. #include <netinet/in.h> // for sockaddr_in

  2. #include <sys/types.h> // for socket

  3. #include <sys/socket.h> // for socket

  4. #include <unistd.h>

  5. #include <stdio.h> // for printf

  6. #include <stdlib.h> // for exit

  7. #include <string.h> // for bzero

  8. #include <string>

  9. #include <google/protobuf/message_lite.h>

  10. #include <google/protobuf/io/coded_stream.h>

  11. #include <google/protobuf/io/zero_copy_stream_impl_lite.h>

  12. #include "infor.pb.h"

  13.  
  14. #define HELLO_WORLD_SERVER_PORT 8000

  15. #define LENGTH_OF_LISTEN_QUEUE 20

  16. #define BUFFER_SIZE 1024

  17. #define FILE_NAME_MAX_SIZE 512

  18.  
  19. int main()

  20. {

  21. std::string time = "2015-06-25";

  22. std::string version = "0.0.1";

  23. double config = 2.0;

  24. double dfs = 3.0;

  25. int file = 1000;

  26. int rep = 1000;

  27. int block = 1000;

  28. int live = 1000;

  29. int de = 1000;

  30.  
  31. struct sockaddr_in server_addr;

  32. bzero(&server_addr,sizeof(server_addr));

  33. server_addr.sin_family = AF_INET;

  34. server_addr.sin_addr.s_addr = htons(INADDR_ANY);

  35. server_addr.sin_port = htons(HELLO_WORLD_SERVER_PORT);

  36.  
  37. int server_socket = socket(PF_INET,SOCK_STREAM,0);

  38. if( server_socket < 0)

  39. {

  40. printf("Create Socket Failed!");

  41. exit(1);

  42. }

  43.  
  44. int opt =1;

  45. setsockopt(server_socket,SOL_SOCKET,SO_REUSEADDR,&opt,sizeof(opt));

  46.  
  47.  
  48. if( bind(server_socket,(struct sockaddr*)&server_addr,sizeof(server_addr)))

  49. {

  50. printf("Server Bind Port : %d Failed!", HELLO_WORLD_SERVER_PORT);

  51. exit(1);

  52. }

  53.  
  54. if ( listen(server_socket, LENGTH_OF_LISTEN_QUEUE) )

  55. {

  56. printf("Server Listen Failed!");

  57. exit(1);

  58. }

  59. while (1)

  60. {

  61.  
  62. struct sockaddr_in client_addr;

  63. socklen_t length = sizeof(client_addr);

  64.  
  65. int new_server_socket = accept(server_socket,(struct sockaddr*)&client_addr,&length);

  66. if ( new_server_socket < 0)

  67. {

  68. printf("Server Accept Failed!\n");

  69. break;

  70. }

  71.  
  72.  
  73. my_message mm;

  74. mm.set_startedtime(time);

  75. mm.set_version(version);

  76. mm.set_configuredcapacity(config);

  77. mm.set_dfsused(dfs);

  78. mm.set_filenum(file);

  79. mm.set_replicatedfilesnum(rep);

  80. mm.set_blocknum(block);

  81. mm.set_livednodenum(live);

  82. mm.set_decommissioningnodenum(de);

  83. file += 1; rep += 1; block += 1; live += 1; de += 1;

  84.  
  85.  
  86. int len = mm.ByteSize() + 4;

  87. char *buffer = new char[len];

  88.  
  89. google::protobuf::io::ArrayOutputStream arrayOut(buffer, len);

  90. google::protobuf::io::CodedOutputStream codedOut(&arrayOut);

  91.  
  92. codedOut.WriteVarint32(mm.ByteSize());

  93.  
  94. //write protobuf ack to buffer

  95. mm.SerializeToCodedStream(&codedOut);

  96.  
  97. //mm.SerializeToArray(buffer, len);

  98.  
  99. if(send(new_server_socket,buffer,len,0)<0)

  100. {

  101. printf("Send File:\t%s Failed\n", "ddddd");

  102. break;

  103. }

  104.  
  105. close(new_server_socket);

  106. delete buffer;

  107. }

  108. close(server_socket);

  109. return 0;

  110. }


java接收线程,通过beancopy更新到数据中心

 

 

 
  1. package com.wy.web;

  2.  
  3. import java.io.InputStream;

  4. import java.net.Socket;

  5. import java.net.UnknownHostException;

  6.  
  7. import com.wy.util.BeanUtil;

  8. import com.wy.web.Infor.my_message;

  9.  
  10. /**

  11. * 数据监听线程,从服务器端取得数据并更新到数据中心

  12. */

  13. public class dataListennerT extends Thread{

  14.  
  15. private Socket socket;

  16. private DataCenter dataCenter;

  17. private static final String host="10.9.3.45";

  18. //private static final String host="10.9.3.165";

  19. public dataListennerT(DataCenter dataCenter) {

  20. this.dataCenter=dataCenter;

  21. }

  22.  
  23. @Override

  24. public void run() {

  25. while(true)

  26. {

  27. try {

  28. Thread.sleep(1000);

  29. } catch (InterruptedException e1) {

  30. // TODO Auto-generated catch block

  31. e1.printStackTrace();

  32. }

  33. try {

  34. socket = new Socket(host,8000);

  35.  
  36. System.out.println("成功连接");

  37.  
  38.  
  39. read(socket);

  40.  
  41.  
  42. } catch (UnknownHostException e) {

  43. // TODO Auto-generated catch block

  44. e.printStackTrace();

  45. } catch (Exception e) {

  46. // TODO Auto-generated catch block

  47. e.printStackTrace();

  48. }

  49. }

  50. }

  51.  
  52. private void read(Socket socket) {

  53. InputStream clientIs;

  54. try {

  55. clientIs = socket.getInputStream();

  56. //Infor.my_message ms = Infor.my_message.parseDelimitedFrom(clientIs);

  57.  
  58. /*-------------------------------*/

  59. byte[] arr = new byte[256];

  60. int len = clientIs.read(arr);

  61. byte[] data=new byte[len];

  62. for(int i=0;i<len;i++)

  63. data[i]=arr[i];

  64.  
  65.  
  66. Infor.my_message ms = Infor.my_message.parseFrom(data);

  67.  
  68.  
  69.  
  70. System.out.println(ms.getStartedTime());

  71. //updataCenter(ms);

  72. BeanUtil.beanFieldCopy(ms, dataCenter, "Csi",true);

  73.  
  74. } catch (Exception e) {

  75. // TODO Auto-generated catch block

  76. e.printStackTrace();

  77. }

  78.  
  79.  
  80. }

数据中心

 

 

 
  1. package com.wy.web;

  2.  
  3. import org.primefaces.push.annotation.Singleton;

  4.  
  5. /**

  6. * 数据中心,从服务器取所有前台需要的数据

  7. */

  8. public class DataCenter {

  9.  
  10. private static DataCenter instance;

  11.  
  12. private String csiStartedTime = "20150624";

  13. private String csiVersion = "1.0.0";

  14. private double csiConfiguredCapacity = 1;

  15. private double csiDfsUsed = 1024;

  16. private int csiFileNum = 26;

  17. private int csiReplicatedFilesNum = 100;

  18. private int csiBlockNum;

  19. private int csiLivedNodeNum = 3;

  20. private int csiDecommissioningNodeNum = 0;

  21.  
  22. public String getCsiStartedTime() {

  23. return csiStartedTime;

  24. }

  25.  
  26. public void setCsiStartedTime(String csiStartedTime) {

  27. this.csiStartedTime = csiStartedTime;

  28. }

  29.  
  30. public String getCsiVersion() {

  31. return csiVersion;

  32. }

  33.  
  34. public void setCsiVersion(String csiVersion) {

  35. this.csiVersion = csiVersion;

  36. }

  37.  
  38. public double getCsiConfiguredCapacity() {

  39. return csiConfiguredCapacity;

  40. }

  41.  
  42. public void setCsiConfiguredCapacity(double csiConfiguredCapacity) {

  43. this.csiConfiguredCapacity = csiConfiguredCapacity;

  44. }

  45.  
  46. public double getCsiDfsUsed() {

  47. return csiDfsUsed;

  48. }

  49.  
  50. public void setCsiDfsUsed(double csiDfsUsed) {

  51. this.csiDfsUsed = csiDfsUsed;

  52. }

  53.  
  54. public int getCsiFileNum() {

  55. return csiFileNum;

  56. }

  57.  
  58. public void setCsiFileNum(int csiFileNum) {

  59. this.csiFileNum = csiFileNum;

  60. }

  61.  
  62. public int getCsiReplicatedFilesNum() {

  63. return csiReplicatedFilesNum;

  64. }

  65.  
  66. public void setCsiReplicatedFilesNum(int csiReplicatedFilesNum) {

  67. this.csiReplicatedFilesNum = csiReplicatedFilesNum;

  68. }

  69.  
  70. public int getCsiLivedNodeNum() {

  71. return csiLivedNodeNum;

  72. }

  73.  
  74. public void setCsiLivedNodeNum(int csiLivedNodeNum) {

  75. this.csiLivedNodeNum = csiLivedNodeNum;

  76. }

  77.  
  78. public int getCsiDecommissioningNodeNum() {

  79. return csiDecommissioningNodeNum;

  80. }

  81.  
  82. public void setCsiDecommissioningNodeNum(int csiDecommissioningNodeNum) {

  83. this.csiDecommissioningNodeNum = csiDecommissioningNodeNum;

  84. }

  85.  
  86. public int getCsiBlockNum() {

  87. return csiBlockNum;

  88. }

  89.  
  90. public void setCsiBlockNum(int blockNum) {

  91. this.csiBlockNum = blockNum;

  92. }

  93.  
  94. public static DataCenter getClient() {

  95. if (instance == null) {

  96. synchronized (Singleton.class) {

  97. if (instance == null) {

  98. instance = new DataCenter();

  99. }

  100. }

  101. }

  102. return instance;

  103. }

  104.  
  105. private DataCenter() {

  106. //System.out.println("DataCenter!!!==========");

  107. new dataListennerT(this).start();

  108.  
  109. }

  110. }


bean copy,实现将两个类属性复制

 

 

 
  1. package com.wy.util;

  2.  
  3. import java.lang.reflect.Field;

  4. import java.lang.reflect.Method;

  5. import java.util.HashSet;

  6.  
  7. public class BeanUtil {

  8.  
  9. public BeanUtil() {

  10.  
  11. }

  12.  
  13. public static synchronized void beanFieldCopy(Object src, Object des, String prefix,boolean desPrefix) {

  14. Class srcClass = src.getClass();

  15. Class desClass = des.getClass();

  16. HashSet<String> setFields = new HashSet<String>();

  17.  
  18. Method[] srcMethods = srcClass.getMethods();

  19. Method[] desMethods = desClass.getMethods();

  20.  
  21. //System.out.println(desClass.getName());

  22.  
  23. // 保存提供set方法的参数

  24. for (int i = 0; i < desMethods.length; i++) {

  25. Method desMethod = desMethods[i];

  26. String desMethodName = desMethod.getName();

  27.  
  28. if (desMethodName.startsWith("set"))

  29. {

  30. if(desPrefix)

  31. setFields.add(desMethodName.substring(3 + prefix.length(),

  32. desMethodName.length()));

  33. else

  34. setFields.add(desMethodName.substring(3,

  35. desMethodName.length()));

  36. }

  37. }

  38. // if(desClass.getName().equals("com.wy.web.ClusterSummaryInfo"))

  39. // System.out.println(setFields);

  40.  
  41. // Field[] desFields = desClass.getDeclaredFields();

  42.  
  43. for (int i = 0; i < srcMethods.length; i++) {

  44. Method method = srcMethods[i];

  45. String srcMethodName = method.getName();

  46. if (srcMethodName.startsWith("get")) {

  47. String fieldName;

  48. if(desPrefix)

  49. fieldName = srcMethodName.substring(3, srcMethodName.length());

  50. else

  51. fieldName=srcMethodName.substring(3+prefix.length(), srcMethodName.length());

  52. // if(desClass.getName().equals("com.wy.web.ClusterSummaryInfo"))

  53. // System.out.println(fieldName);

  54. if (setFields.contains(fieldName)) {

  55. String invokeMethodName;

  56. if(desPrefix)

  57. invokeMethodName= "set" + prefix + fieldName;

  58. else

  59. invokeMethodName="set"+fieldName;

  60. //System.out.println(desClass.getName()+" "+invokeMethodName);

  61. try {

  62. Method invokeMethod = desClass.getMethod(

  63. invokeMethodName,

  64. new Class[] { method.getReturnType() });

  65. Object result = method.invoke(src, new Object[] {});

  66. if (result == null)

  67. break;

  68.  
  69. invokeMethod.invoke(des, new Object[] { result });

  70.  
  71. } catch (Exception e) {

  72. // TODO Auto-generated catch block

  73. e.printStackTrace();

  74. }

  75.  
  76. }

  77.  
  78. }

  79. }

  80.  
  81. }

  82.  
  83.  
  84. }

--------------------- 本文来自 chicc999 的CSDN 博客 ,全文地址请点击:https://blog.csdn.net/chicc999/article/details/46687291?utm_source=copy

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值