void *send_data(void *arg) //这是一个发送数据的线程
{
int sockfd = init_tcp_cli("192.168.0.148",50000)
//传ip和port,port == 50000是因为大概前五万都被其它服务所占用,50000后是私人ip
if(sockfd < 0)
{
return NULL;
}
unsigned char pack[128] = {0};
int len = 0;
while(1)
{
len = pack_net_data(data_g,pack)
//data_g是一个保存数据的结构体的全局变量
ssize_t size = send(sockfd,pack,len,0)
if(size < 0)
{
perror("fail send:");
break;
}
sleep(1)
//这里是为了一秒发送一次数据
}
close(sockfd);
return NULL;
}
初始化cli和包装数据:
int init_tcp_cli(const char *ip,unsigned short port)
{
int sockfd = socket(AF_INET,SOCK_STREAM,0)
if(sockfd < 0)
{
perror("fail socket:");
return -1;
}
struct sockaddr_in ser;
ser.sin_family = AF_INET;
ser.sin_port = htons(port);
ser.sin_addr.s_addr = inet_addr(ip);
int ret = connect(sockfd,(struct sockaddr *)&ser,sizeof(ser));
if(ret < 0)
{
perror("fail connect:");
return -1;
}
return sockfd;
}
int pack_net_data(Data_t data,unsigned char *pack)
{
int i = 0;
pack[i++] = 0xAA; //帧头
pack[i++] = 20; //根据协议确定的有效数据长度
memcpy(&pack[i],&data.temp,sizeof(data.temp)); //把数据拷贝到pack中
i += sizeof(data.temp); //下标往后移
pack[i++] = data.tim.tm_sec;
//把秒数放入pack,因为其它数据的写法都一样,就不写完了
for(int j = 1; j < i;++j) //8位和校验
{
pack[i] += pack[j];
}
++i;
pack[i] = 0xBB //帧尾
++i;
return i;
}