#include <iostream>
#include <sys/types.h> /* See NOTES */
#include <sys/socket.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "test.pb.h" /* 这是proto文件生成的头文件 */
#include "include/google/protobuf/map.h"/* protobuf提供的map数据结构 */
using namespace std;
int connect_server()
{
int fd = 0;
struct sockaddr_in addr;
int len = 0;
char *pcData = NULL;
long fileSize = 0;
fd = socket(AF_INET, SOCK_STREAM, 0);
if (fd < 0)
{
printf("socket() failed .\n");
return -1;
}
memset(&addr, 0, sizeof(struct sockaddr_in));
addr.sin_family = AF_INET;
addr.sin_port = htons(8888);
addr.sin_addr.s_addr = inet_addr("127.0.0.1");
if (connect(fd, (struct sockaddr *)&addr, sizeof(struct sockaddr_in)))
{
printf("connect() failed .\n");
return -1;
}
commun::Say msg;
//基本类型参数的赋值
msg.set_code(13); //数值型
msg.set_data("this is the last chance, go ,do not hesitate .\n"); //字符串类型
//读一个音频文件
readAudio("../audio/test.wav", &pcData,&fileSize);
//非字符串型字符数据赋值(例如音频文件)
//注意需要加size,不然传过去就是字符串,字符串是以0结尾的
msg.set_audio(pcData, fileSize);
msg.set_filesize(fileSize);
//数组类型参数的赋值--proto文件中repeated修饰的变量
msg.add_name("feng");
msg.add_name("yu");
msg.add_name("lei");
msg.add_name("dian");
//map类型参数的赋值
using MapPair = google::protobuf::MapPair<google::protobuf::int32, string>;
msg.mutable_projects()->insert(MapPair(0, "tom"));
msg.mutable_projects()->insert(MapPair(1, "jack"));
msg.mutable_projects()->insert(MapPair(2, "dong"));
len = htonl(msg.ByteSize());
//msg.ByteSize()获取消息结构的大小
char *buffer = (char *)malloc(msg.ByteSize()+4);
memset(buffer, 0, msg.ByteSize() + 4);
//存放消息结构的大小
memcpy(buffer, &len, sizeof(int));
//将消息msg序列化到buffer中
//也可以使用SerializeToString()函数来序列化字符串,但是估计没啥应用场景
//ParseFromString()反序列化字符串
//ParseFromArray()反序列化字符数组
msg.SerializeToArray(buffer + 4, msg.ByteSize());
send(fd, buffer, msg.ByteSize()+4, 0);
free(buffer);
sleep(30);
close(fd);
return 0;
}