socketswaittcpclient

TCP Client with select , after connect waits for input


I've ran into a problem with a simple TCP Client implemented using select.

The problem is that,at the second printf it only displays before it gets to the connect() function then waits for user input. Does connect block the rest of the program until i send something? (The TCP server is also implemented using select but i didn't find anything wrong with it) I've searched on the web and couldn't find a cause or maybe i didn't search for the right thing..

#include <includes.h>
int main()
{
int sfd;
fd_set rset;
char buff[1024]=" ";
char playerName[20]="";
int nameSet=0;
struct sockaddr_in server;
sfd= socket(AF_INET,SOCK_STREAM,0);

if(sfd<0)
 { printf("socket not created\n");   return 0; }
bzero(&server,sizeof(struct sockaddr_in));
server.sin_family=AF_INET;
server.sin_port=htons(2020);
inet_aton("127.0.0.1",&server.sin_addr);
  //here is the problem after %d which calls the connect() function
printf("Conexion returned:%d \n  Name:",connect(sfd,(struct sockaddr *)&server,sizeof(server)));
 for(;;)
 {
 bzero(buff,1024);

 FD_ZERO(&rset);
 FD_SET(0,&rset);
 FD_SET(sfd,&rset);
     if(select(sfd+1,&rset,NULL,NULL,NULL)<0)
     {
         printf("con-lost!\n");
         break;
     }

     if(FD_ISSET(0,&rset))
     {
     printf("Talk: \n");
     scanf("%s",buff);
     if(nameSet==0)
     {
         strcpy(playerName,buff);
         nameSet=1;
         printf("Hi:%s\n",playerName);
     }
         if(write(sfd,buff,strlen(buff)+10)<0)
         {
             break;
         }
     }

      if(FD_ISSET(sfd,&rset)>0)
     {
         if(read(sfd,buff,1024)<=0)
         {
         printf("con is off!\n");
         break;
         }
     printf("msg rcd %s\n",buff);
     }

   } //endfor
   close(sfd);
   return 0;
 } //endmain

Solution

  • The connect function, on a blocking socket, blocks until the connect operation succeeds or fails.

    You should be warned that using select with a blocking socket, which is what your program does, does not ensure that your program will not block. When you get a select hit, that does not guarantee that a future operation will not block.

    strlen(buff)+10
    

    What's the reasoning behind the +10?