任何想法为什么当服务器在客户端等待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, &address, 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, 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");
}
}
答案 0 :(得分:8)
要选择的第一个参数应该是最大套接字ID加1.因此,在您的情况下,它应该是
socket_desc+1
你能尝试一下,看看它是否有效?
当你按下键盘上的键时它才会得到的原因是因为stdin为0,这将在0 - (3 - 1)范围内,这是检查的内容。如果将第一个参数设置为socket_desc + 1,则应检查0 - (socket_desc)范围是否为就绪套接字