资源描述:
《linux-c基于udp的多人聊天程序》由会员上传分享,免费在线阅读,更多相关内容在工程资料-天天文库。
1、Client.C#include#include#includevstring・h>#include#include#include#ineludevnetinet/in.h>#include#include#include#defineN128typedefstruct{chartype;charname[32];chartext[N];
2、}MSG;intmain(intargc,char*argv[]){intsocketfd;socklentaddrlen;pid_tpid;MSGmsg;structsockaddrjnserver_addr;if(argc<3){printf(Huasge:%sipport%rgv[0]);exit(-l);}if((socketfd=socket(PF」NET,SOCK_DGRAM,0))<0){perror(Msocket");exit(-l);}printf(ninputname:H);fget
3、sfmsg.name,64,stdin);msg.name[strlen(msg.name)-1]=、0‘;msg.type=,L,;memset(&server_addr,0,sizeof(server_addr));server^addr.sin_family=AF」NET;server_addr.sin_addr.s_addr=inet_addr(argv[l]);server_addr.sin_port=htons(atoi(argv[2]));addrjen=sizeof(server_addr);if
4、(sendtofsocketfd,&msg,sizeof(msg),0‘(structsockaddr*)&server_addr,addr_len)<0){perror(Hsendto3H);exit(-l);}if((pid=fork())==-1){perrorCfork1');exit(-l);}iffpid==0){while(l){fgets(msg.text,N,stdin);msg.text[strlen(msg.text)-1]=* ';iffstrncmpfmsg.text/'quitM)=
5、=0){msg.type=Q;if(sendto(socketfd,&msEsizeof(msg),0’(structsockaddr*)&server_addr,addr_len)<0)perror(”sendto2j;exit(-l);}kill(getppid(),SIGKILL);break;}elsemsg.type=,B,;if(sendto(socke廿d,&msg^izeoffmsgl^O^structsockaddr*)&server_addr,addr_len)perror(Hsendtol”
6、);}}close(socketfd);}if(pid>0){while(l){if(recvfrom(socketfd,&msg’sizeof(rnsg),0‘(structsockaddr*)&server_addr,&addr_len)<0){perror(HrecvfromH);exit(-l);}switch(msg.type){case1':printf("%slogin舄msg.name);break;case'B':printf(Hfrom%s>%s舄msg.name.msg.text);
7、break;caseQ:printf(u%squit蔦msg.name);break;}}}return0;}server.c#include#include#include#include#include#include#includevnetinet/in.h>#include#include#include#d
8、efineN128#defineL1#defineB2#defineQ3typedefstruct{chartype;charname[32];chartext[N];}MSG;typedefstructnode{structsockaddr_inaddr;structnode*next;}listnode,*linklist;linklistlinklist_creat