udp实现c/s服务器模型
Posted 药剂学徒
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了udp实现c/s服务器模型相关的知识,希望对你有一定的参考价值。
server
#include<stdio.h> #include<unistd.h> #include<sys/socket.h> #include<sys/types.h> #include<ctype.h> #include<strings.h> #include<arpa/inet.h> #include<string.h> #define port 8000 #define buflen 1024 int main(void){ int sfd; char buf[buflen]; char client_ip[128]; socklen_t addrlen; struct sockaddr_in serv_addr ,client_addr; int i; int len ; sfd = socket(AF_INET,SOCK_DGRAM,0); bzero(&serv_addr,sizeof(serv_addr)); serv_addr.sin_family = AF_INET; serv_addr.sin_port = htons(port); serv_addr.sin_addr.s_addr = htonl(INADDR_ANY); bind(sfd,(struct sockaddr*)&serv_addr,sizeof(serv_addr)); while(1){ addrlen = sizeof(client_addr); len = recvfrom(sfd,buf,sizeof(buf),0,(struct sockaddr*)&client_addr,&addrlen); printf("client ip:%s\t port:%d\n",inet_ntop(AF_INET,&client_addr.sin_addr.s_addr,client_ip,sizeof(client_ip)),ntohs(client_addr.sin_port)); for(i = 0;i<len;i++){ buf[i] = toupper(buf[i]); } sendto(sfd,buf,len,0,(struct sockaddr*)&client_addr,addrlen); } close(sfd); return 0; }
client:
#include<stdio.h> #include<unistd.h> #include<sys/socket.h> #include<sys/types.h> #include<ctype.h> #include<strings.h> #include<arpa/inet.h> #include<string.h> #define port 8000 #define buflen 1024 #define IP "127.0.0.1" int main(int argc,char* argv[]){ int sfd; char buf[buflen]; struct sockaddr_in serv_addr; socklen_t addrlen; int i,len; sfd = socket(AF_INET,SOCK_DGRAM,0); bzero(&serv_addr,sizeof(serv_addr)); serv_addr.sin_family = AF_INET; serv_addr.sin_port = htons(port); inet_pton(AF_INET,IP,&serv_addr.sin_addr.s_addr); //serv_addr.sin_addr.s_addr = htonl(INADDR_ANY); while(1){ fgets(buf,sizeof(buf),stdin); addrlen = sizeof(serv_addr); sendto(sfd,buf,strlen(buf),0,(struct sockaddr*)&serv_addr,addrlen); len = recvfrom(sfd,buf,sizeof(buf),0,NULL,0); buf[len] = "\0"; printf("%s",buf); } close(sfd); return 0; }
以上是关于udp实现c/s服务器模型的主要内容,如果未能解决你的问题,请参考以下文章