UDP循坏服务器实现方法:UDP服务器每次从套接字上读取一个客户端的请求并处理,然后将处理结果返回给客户端。
算法流程:
socket();bind();
while(1){
recvfrom();
process();
sendto();
}
因为UDP是无连接的,没有一个客户端可以一直占用服务器,服务器能满足每一个客户端的请求。
服务端代码:udpserver.cpp
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<string.h>
#include<unistd.h>
#include<errno.h>
#include<iostream>
#include<stdio.h>
#include<stdlib.h>
using namespace std;
int main(int argc , char* argv[]){
int sockFd,ret,size;
char on=1;
sockFd=socket(AF_INET,SOCK_DGRAM,0);
if(sockFd<0){
puts("Create socket failed!");
return -1;
}
size=sizeof(sockaddr_in);
sockaddr_in saddr,raddr;
saddr.sin_family=AF_INET;
saddr.sin_addr.s_addr=inet_addr(argv[1]);
saddr.sin_port=htons(atoi(argv[2]));
//设置端口复用
setsockopt(sockFd,SOL_SOCKET,SO_REUSEADDR,&on,sizeof(on));
//绑定地址信息
ret=bind(sockFd,(sockaddr*)&saddr,size);
if(ret<0){
puts("Bind failed!");
return -1;
}
int val=sizeof(sockaddr);
char rbuf[50],sbuf[100];
//循坏接收消息
while(1){
puts("waiting data");
ret=recvfrom(sockFd,rbuf,50,0,
(sockaddr*)&raddr,(socklen_t*)&val);
if(ret<0){
perror("recvfrom failed!");
}
printf("recv data :%s\n",rbuf);
sprintf(sbuf,"server has received your data(%s)\n",rbuf);
ret=sendto(sockFd,sbuf,strlen(sbuf),0,(sockaddr*)&raddr,val);
memset(rbuf,0,50);
}
close(sockFd);//关闭udp套接字
return 0;
}
客户端代码:udpclient.cpp
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<string.h>
#include<unistd.h>
#include<errno.h>
#include<iostream>
#include<stdio.h>
#include<stdlib.h>
using namespace std;
int main(int argc,char* argv[]){
int sockFd=socket(AF_INET,SOCK_DGRAM,0);
if(sockFd<0){
puts("Create socket failed!");
return -1;
}
sockaddr_in saddr,raddr;
int size=sizeof(saddr);
saddr.sin_family=AF_INET;
saddr.sin_addr.s_addr=inet_addr(argv[1]);
saddr.sin_port=htons(atoi(argv[2]));
char on=1;
int val=sizeof(sockaddr);
char sbuf[50],rbuf[100];
setsockopt(sockFd,SOL_SOCKET,SO_REUSEADDR,&on,sizeof(on));
while(1){
puts("Please enter data:");
scanf("%s",sbuf,sizeof(sbuf));
int ret=sendto(sockFd,sbuf,50,0,(sockaddr*)&saddr,val);
if(ret<0){
perror("Send data failed!");
}
ret=recvfrom(sockFd,rbuf,sizeof(rbuf),0,
(sockaddr*)&raddr,(socklen_t*)&val);
if(ret<0)
perror("Recv failed!");
puts(rbuf);
memset(rbuf,0,sizeof(rbuf));
memset(sbuf,0,sizeof(sbuf));
}
close(sockFd);
return 0;
}
代码测试结果: