我正在研究客户端服务器代码,我在客户端运行两个线程(批量和零售),我在服务器上有两个端口来接收数据。我想在服务器端使用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;
}
答案 0 :(得分:0)
更改
if(FD_ISSET(i, &readfds)){
if(i == sd){
...
}
else if(FD_ISSET(i, &readfds)){
if(i == sd1){
...
}
}
到
if(FD_ISSET(i, &readfds)){
if(i == sd){
...
}
else if(i == sd1){
...
}
}
在代码中,第二个外部if永远不会到达。你实际上有if (x) then y; else if (x) then z;
显然,第二个if永远不会到达。