任何想法为什么当服务器在客户端等待select时选择套接字时,select永远不会完成?
我使用c在套接字之间进行通信.我的客户端连接到我的服务器很好.
socket_desc=socket(AF_INET,SOCK_STREAM,0);//create the socket descriptor client->address.sin_addr.s_addr = inet_addr(ipAddress); client->address.sin_family = AF_INET; client->address.sin_port = htons(port); bind(socket_desc,&address,sizeof(address)); connect(socket_desc,sizeof(address));
当我使用recv来阻止和监听数据时,一切正常:
int bytesRead = 1; while(bytesRead){ int bufsize=1024; char *buffer=malloc(bufsize); bytesRead = recv(socket_desc,buffer,bufsize,0); printf("CLIENT RECV: %s",buffer); }
如果我尝试使用select,它似乎不会读取任何数据.如果我将STDIN添加到fd_set,我可以强制它从套接字读取,但是select似乎没有从socket_desc中读取数据…?
int running = 1; while(running){ /* wait for something to happen on the socket */ struct timeval selTimeout; selTimeout.tv_sec = 2; /* timeout (secs.) */ selTimeout.tv_usec = 0; /* 0 microseconds */ fd_set readSet; FD_ZERO(&readSet); FD_SET(STDIN_FILENO,&readSet);//stdin manually trigger reading FD_SET(socket_desc,&readSet);//tcp socket int numReady = select(3,&readSet,NULL,&selTimeout); //IT ONLY GETS PAST SELECT ON RETURN FROM THE KEYBOARD if(numReady > 0){ char buffer[100] = {'\0'}; int bytesRead = read(socket_desc,&buffer,sizeof(buffer)); printf("bytesRead %i : %s",bytesRead,buffer); if(bytesRead == 0){ running = FALSE; printf("Shutdowning client.\n"); } }