网络客户端利用TCP数据流上传随机生成的温度数据给主控程序
net_client.c
#include<stdio.h>
#include<stdlib.h>
#include<errno.h>
#include<string.h>
#include<netdb.h>
#include<fcntl.h>
#include<sys/socket.h>
#include<sys/types.h>
#include<netinet/in.h>
int main(int argc, char *argv[])
{
int port;
int sockfd,nread;
struct sockaddr_in server_addr;
unsigned char data[5];
if(argc < 3){
printf("please input server IP,PORT.\n");
exit(0);
}
port = atoi(argv[2]);
if(port<1024){
printf("port error\n");
exit(0);
}
if((sockfd=socket(AF_INET,SOCK_STREAM,0))==-1){
fprintf(stderr,"Socket Error:%s\a\n",strerror(errno));
exit(1);
}
bzero(&server_addr,sizeof(server_addr));
server_addr.sin_family=AF_INET;
server_addr.sin_port=htons(port);
server_addr.sin_addr.s_addr=inet_addr(argv[1]);
if(connect(sockfd,(struct sockaddr *)(&server_addr),sizeof(struct sockaddr))==-1)
{
fprintf(stderr,"Connect Error:%s\a\n",strerror(errno));
exit(1);
}
while(1){
sleep(2);
data[0]=rand()%100;//模拟产生温度数据
if((nread=send(sockfd,data,1,0))==-1){
printf("send error\n");
break;
}else{
//printf("%x,%x\n",data[0],data[1]);
}
}
close(sockfd);
exit(0);
}
运行结果如下图: