我正在处理客户端服务器代码,其中我有两个线程在客户端运行(散装和零售),并且我在服务器上有两个端口来接收数据。我想在服务器端使用 select() 但犯了一些错误,因为“sd1 - 这是大容量端口”永远不会收到数据。如果有人可以帮助我了解如何继续使用当前代码,我将不胜感激。谢谢!!
int main(int argc, char *argv[]) {
fd_set readfds, activefds;
// SOCKET CREATION RETAIL
sd=socket(AF_INET, SOCK_DGRAM, 0);
if(sd<0) {
printf("error creating retail socket \n");
return -1;
}
// SOCKET CREATION BULK
sd1=socket(AF_INET, SOCK_DGRAM, 0);
if(sd1<0) {
printf("error creating retail socket \n");
return -1;
}
// BIND RETAIL PORT
servAddr.sin_family = AF_INET;
servAddr.sin_addr.s_addr = htonl(INADDR_ANY);
servAddr.sin_port = htons(RETAIL_PORT);
rc = bind (sd, (struct sockaddr *) &servAddr,sizeof(servAddr));
if(rc<0) {
printf("error binding retail port number %d \n",RETAIL_PORT);
return -1;
}
// BIND BULK PORT
servAddr.sin_family = AF_INET;
servAddr.sin_addr.s_addr = htonl(INADDR_ANY);
servAddr.sin_port = htons(BULK_PORT);
rc1 = bind (sd1, (struct sockaddr *) &servAddr,sizeof(servAddr));
if(rc1<0) {
printf("error binding bulk port number %d \n",BULK_PORT);
return -1;
}
int nfds;
if(sd>sd1){
nfds = sd;}
else{
nfds = sd1;}
FD_ZERO(&activefds);
FD_SET(sd, &activefds);
FD_SET(sd1, &activefds);
while(1){
readfds = activefds;
if (select(nfds+1, &readfds, NULL, NULL, NULL) < 0){
perror("select");
break;
}
for(i=0;i<nfds;i++){
if(FD_ISSET(i, &readfds)){
printf("sd = %d\n\n\n",sd); // sd = 3 getting printed here
if(i == sd){
n = recvfrom(sd, &requested_retail_cases, 4, 0, (struct sockaddr *) &cliAddr, &cliLen);
printf("in retail\n");
}
else if(FD_ISSET(i, &readfds)){
if(i == sd1){
n1 = recvfrom(sd1, &requested_bulk_cases, 4, 0, (struct sockaddr *) &cliAddr, &cliLen);
}
}
}
}
return 1;
}