Using selections to wait for data on a client socket

Any ideas why, when the server writes the socket, when the client waits for the select, the choice never ends?

I use c for communication between sockets. My client connects perfectly to my server.

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)); 

When I use recv to lock and listen to data, everything works fine:

 int bytesRead = 1; while(bytesRead){ int bufsize=1024; char *buffer=malloc(bufsize); bytesRead = recv(socket_desc, buffer, bufsize, 0); printf("CLIENT RECV: %s", buffer); } 

If I try to use select, it does not seem to read any data. If I add STDIN to fd_set, I can make it read from the socket, but the selection does not seem to start from reading socket_desc in the data ...?

 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"); } } 
+6
c select sockets
source share
1 answer

The first parameter to choose should be the maximum socket identifier plus 1. Thus, in your case, it should be

 socket_desc+1 

Can you try and see if it works?

The reason that it appears only when you press a key on the keyboard is because stdin is 0, which will be within the 0 - (3 - 1) range, which was checked. If you set the first parameter to socket_desc + 1, then for ready-made sockets you should check the range 0 - (socket_desc)

+8
source share

All Articles