这是我的服务器。我想使用UDP创建迭代服务器,但它的客户端不会退出,第二个客户端会收到消息。这不是迭代服务器。你能告诉我一个方法让新客户等到第一个客户退出吗?
------------ UDP ITERATIVE SERVER ----------
#include <iostream>
#include "config.h"
#include <arpa/inet.h>
#include "unp.h"
using namespace std;
int main() {
int sockfd=socket(AF_INET,SOCK_DGRAM,0);
if (sockfd==-1) {
cout<<"ERROR WHILE CREATING SOCKET"<<endl;
exit(0);
}
else {
cout<<"SOCKET CREATED SUCCESSFULLY"<<endl;
}
struct sockaddr_in server;
server.sin_port=htons(4444);
server.sin_family=AF_INET;
memset(&(server.sin_zero),'\0',8);
server.sin_addr.s_addr=inet_addr("127.0.0.1");
int trybind=bind(sockfd,(struct sockaddr*)&server,sizeof(struct sockaddr));
if (trybind==-1) {
cout<<"ERROR WHILE BINDING ..."<<endl;
exit(0);
}
char msg[100],tosend[100];
if (trybind==0) {
cout<<"binded successfully"<<endl;}
while(1) {
struct sockaddr_in client;
socklen_t sizee=sizeof(client);
while(recvfrom(sockfd,msg,100,0,(struct sockaddr*)&client,&sizee)) {
cout<<"CLIENT : "<<msg<<endl;
cout<<"[CLIENT's PORT NUMBER :]"<<htons(client.sin_port)<<endl ;
char* clientip[100];
//socklen_t sizE=sizeof(client);
//clientip=inet_ntop(AF_INET, &(client.sin_addr), clientip, &sizee);
cout<<"[CLIENT's IP Address :] "<<inet_ntoa(client.sin_addr)<<endl;
if (strcmp(msg,"quit")!=0) {
cout<<"SERVER :";
cin.getline(tosend,100);
cout<<endl;
int sen=sendto(sockfd,tosend,100,0,(struct sockaddr*)&client,sizee);
}
}
}
}
}
*************客户***********
#include <iostream>
#include "config.h"
#include "unp.h"
using namespace std;
int main() {
int sockfd=socket(AF_INET,SOCK_DGRAM,0);
if(sockfd==-1) {
cout<<"ERROR WHILE CREATING SOCKET"<<endl;
exit(0);
}
else {
cout<<"SOCKET CREATED SUCCESSFULLY"<<endl;
}
struct sockaddr_in server;
server.sin_port=htons(4444);
server.sin_family=AF_INET;
memset(&(server.sin_zero),'\0',8);
server.sin_addr.s_addr=inet_addr("127.0.0.1");
while(1) {
char msg[100],tosend[100];
cout<<"CLIENT:";
cin.getline(tosend,100);
cout<<endl;
if (strcmp(tosend,"quit")==0) {
cout<<"quiting"<<endl;
exit(0);
}
socklen_t sizee=sizeof(server);
int sen=sendto(sockfd,tosend,100,0,(struct sockaddr*)&server,sizee);
//struct sockaddr_in client;
int rec=recvfrom(sockfd,msg,100,0,(struct sockaddr*)&server,&sizee);
cout<<"SERVER : "<<msg<<endl;
}
}