超详细的C++与java使用protobuf进行数据交互
1、安装环境客户端idea,服务端c++,服务端需要linux环境,可以使用远程服务器获取虚拟机都可以2、服务端准备需要安装protobuf环境安装需要的依赖包:yum -y install autoconf automake libtool curl make g++ unzipunzip protobuf-master.zipcd protobuf-master./autogen.sh./co
·
1、安装环境
客户端idea,服务端c++,服务端需要linux环境,可以使用远程服务器获取虚拟机都可以
2、服务端准备
需要安装protobuf环境
- 安装需要的依赖包:
yum -y install autoconf automake libtool curl make g++ unzip
unzip protobuf-master.zip
cd protobuf-master
./autogen.sh
./configure
make
make check
make install
最后查看版本
protoc --version
2、创建用来交换数据格式
infor.proto文件
syntax = "proto2";
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;
}
编译生成.h和cpp文件
protoc --proto_path=./ --cpp_out=./ ./infor.proto
会生成两个文件
3、服务端的主代码
#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 8888
#define LENGTH_OF_LISTEN_QUEUE 20
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 (true)
{
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 my_message mm to CodedOutputStream
mm.SerializeToCodedStream(&codedOut);
if (send(new_server_socket, buffer, len, 0) < 0)
{
printf("Send Failed\n");
break;
}
close(new_server_socket);
delete buffer;
}
close(server_socket);
return 0;
}
makefile文件
prom=server
obj=server.cpp infor.pb.cc
$(prom) : $(obj)
g++ $(obj) -o ./$@ -g -Wall -lpthread -lprotobuf -std=c++11
clean:
rm -rf ./build/$(prom)
生成server可执行文件,至此服务端的准备工作完成
4、客户端的准备工作
idea中安装我的目录结构
infor.proto文件
syntax = "proto2";
option java_package = "com.protobuftest.protobuf";
option java_outer_classname = "CodedInputStream";
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;
}
5、java的主代码,代码中ip地址改为自己的地址和端口
package com.protobuftest.protobuf;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
public class Client {
public static final String IP_ADDR = "139.196.53.139"; //server ip
public static final int PORT = 8888; //port
public static void main(String[] args) throws InterruptedException {
System.out.println("client starting...");
do {
Thread.sleep(1000);
Socket socket = null;
try {
socket = new Socket(IP_ADDR, PORT);
InputStream input = socket.getInputStream();
try{
// 反序列化
CodedInputStream.my_message mm = CodedInputStream.my_message.parseDelimitedFrom(input);
System.out.println("服务器端返回过来的是: ");
System.out.println("startedTime:" + mm.getStartedTime());
System.out.println("version:" + mm.getVersion());
System.out.println("configuredCapacity:" + mm.getConfiguredCapacity());
System.out.println("dfsUsed:" + mm.getDfsUsed());
System.out.println("fileNum:" + mm.getFileNum());
System.out.println("replicatedFilesNum:" + mm.getReplicatedFilesNum());
System.out.println("blockNum:" + mm.getBlockNum());
System.out.println("livedNodeNum:" + mm.getLivedNodeNum());
System.out.println("decommissioningNodeNum:" + mm.getDecommissioningNodeNum());
} catch(Exception e)
{
System.out.println(e.toString());
System.out.println("catch e");
break;
}
input.close();
} catch (Exception e) {
System.out.println("客户端异常:" + e.getMessage());
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
socket = null;
System.out.println("客户端 finally 异常:" + e.getMessage());
}
}
}
}while(false);
}
}
6、window端也要准备编译protocbuf的环境,但不需要像服务端那么麻烦,只需要protoc.exe就可以了
进到官网下载即可
7、对infor.proto文件进行编译,进到与infor.proto同一夹子下再进行编译
D:\download\protoc-3.19.1-win64\bin\protoc.exe --java_out=./ infor.proto
编译出来的java文件会放入对应的包中
8、文件中可能还需要加入
进到官网
https://mvnrepository.com/
点击下载即可
添加jar包即可
至此全部的环境已经准备完成
9、启动服务
先启动服务端的可执行文件
再运行java代码
之后java收到了服务端的数据
更多推荐
已为社区贡献3条内容
所有评论(0)