2.用UDP心跳机制实现2个程序间的通讯 30分程序A使用定时器每5秒向程序B发送一个消息。程序B把收到的消息后,发一个ok给程序A.如果程序A在10秒内没有收到程序B发送的ok消息,就在屏上打印ERROR提示:心跳机制 类似 软件狗的功能, 有一个倒计时的时间,在倒计时完成后没有收到信息,则显示失败,如果在倒计时结束前收到了信息,则重新开始计时。这个功能需要进程专门起一个线程来做这个倒计时的工作。
A:#include <sys/types.h> #include <sys/socket.h> #include<string.h> #include<arpa/inet.h> #include <stdio.h>#include <time.h>int num1=0,num2=0;char buf[100];int s1,s2;time_t time_now ;struct tm *time_p;void * mtime(){ time_now = time(0); //调用系统函数,并初始化 time_p = gmtime(&time_now); printf( "The current time is :%d : %d :%d \n",time_p->tm_hour,time_p->tm_min,time_p->tm_sec ); //临时参数,用来与当前时间比较 s1=s2=time_p->tm_sec; int t1,t2; while (1) { if((t1=(time_p->tm_sec-s1))==5) { s1= time_p->tm_sec; num1=1; } if((t2=(time_p->tm_sec-s2))==10) { s2= time_p->tm_sec; num2=1; } sleep(1); time_now = time(0); time_p = gmtime(&time_now); } }void *mrecv(void * sockfd){ int socklen; struct sockaddr_in servaddr; socklen =sizeof (servaddr); while(1) { if(recvfrom(*((int *)sockfd),buf,10,0,NULL,NULL)<=0) { perror("rexcv error"); } else { time_now = time(0); time_p = gmtime(&time_now); s2= time_p->tm_sec; num2=0; s2= printf("%s\n",buf); } bzero(buf,100); }}int sockfd;void * msock(){ struct sockaddr_in servaddr,cliaddr; if((sockfd=socket(AF_INET,SOCK_DGRAM,0))<0) { perror("socket error"); return ; } bzero (&servaddr,sizeof(servaddr)); servaddr.sin_family=AF_INET; servaddr.sin_port=htons(8884); servaddr.sin_addr.s_addr=inet_addr("127.0.0.1");// bzero(&cliaddr,sizeof(cliaddr)); cliaddr.sin_family= AF_INET; cliaddr.sin_port=htons(7776); cliaddr.sin_addr.s_addr=inet_addr("127.0.0.1"); if (bind(sockfd,(struct sockaddr *)&cliaddr,sizeof(cliaddr))<0) { perror("bind error"); return ; } num1=1; while (1) { if(num1==1) { sendto(sockfd,"OK_server",10,0,(struct sockaddr *)&servaddr,sizeof(servaddr)); num1=0; } if (num2==1) { printf("%s\n","ERROR"); close(sockfd); break; } }}int main () { pthread_t thread_1,thread_2,thread_3; pthread_create(&thread_1,NULL,mtime,NULL); pthread_create(&thread_2,NULL,msock,NULL); pthread_create(&thread_3,NULL,mrecv,(void *)&sockfd); pthread_join(thread_1,NULL); pthread_join(thread_2,NULL); pthread_join(thread_3,NULL); return 0; }
B:#include <sys/types.h>#include <sys/socket.h>#include<string.h>#include<arpa/inet.h>#include <stdio.h>int main (){ int sockfd; struct sockaddr_in myaddr,cliaddr; int socklen; char buf[100],buffer[100]="hello client"; if((sockfd=socket(AF_INET,SOCK_DGRAM,0))<0) { perror("socket error"); return -1; } bzero (&myaddr,sizeof(myaddr)); myaddr.sin_family=AF_INET; myaddr.sin_port=htons(8884); myaddr.sin_addr.s_addr=inet_addr("127.0.0.1");// if(bind(sockfd,(struct sockaddr*)&myaddr,sizeof(myaddr))<0) { perror("bind error"); return -1; } while(1) { socklen=sizeof(cliaddr); recvfrom (sockfd,buf,10,0,(struct sockaddr *)&cliaddr,&socklen); printf("%s\n",buf); sendto (sockfd,"OK_client",10,0,(struct sockaddr *)&cliaddr,socklen); } return 0;}