2017-07-28 1 views
0

Bonjour J'essaye d'écrire une application cliente qui essaiera de connecter un serveur distant. S'il ne peut pas se connecter au serveur, il réessayera après 5 secondes. Si le socket est fermé d'une manière ou d'une autre, il essayera de se connecter à nouveau.problème de connexion de socket client

Je reçois une erreur comme connecter: point final Transport est déjà connecté

Quel pourrait être le problème?

static void sig_chld(int signo) 
{ 

    pid_t pid; 
    int stat; 
    while ((pid = waitpid(-1, &stat, WNOHANG)) > 0) 
     printf("child %d terminated\n", pid); 

    return; 
} 


int main(int argc, char *argv[]) 
{ 

int sockfd, numbytes; 
char buf[MAXDATASIZE]; 
pid_t childpid; 
struct hostent *he; 
struct sockaddr_in their_addr; /* connector's address information */ 

     if ((he=gethostbyname(argv[1])) == NULL) { /* get the host info */ 
      herror("gethostbyname"); 
      exit(1); 
     } 

     if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) { 
      perror("socket"); 
      exit(1); 
     } 

     their_addr.sin_family = AF_INET;  /* host byte order */ 
     their_addr.sin_port = htons(PORT); /* short, network byte order */ 
     their_addr.sin_addr = *((struct in_addr *)he->h_addr); 
     bzero(&(their_addr.sin_zero), 8);  /* zero the rest of the struct */ 


    for (; ;) { 


     while (connect(sockfd, (struct sockaddr *)&their_addr, sizeof(struct sockaddr)) == -1) 
     {    
      perror("connect"); 
       sleep(5); 
      } 


     if ((childpid = fork()) == 0) 
     { /* child process */ 
      while(1) 
      { 

       if (send(sockfd, "Hello, world!\n", 14, 0) == -1) 
       { 
          perror("send"); 
       } 

       sleep(3); 
      } 
      close(sockfd); 

     } 
    } 

     return 0; 
    } 

Répondre

0

Vous ne pouvez pas reconnecter une prise une fois que vous avez même essayé de le connecter avant, même si elle a échoué. Vous devez le fermer et en créer un nouveau.

+0

Alors, quel est votre objectif? Que devrais-je faire dans mon code? – voyvoda

+0

quelqu'un peut-il m'aider ???? – voyvoda

+0

@voyvoda Quelle partie de 'vous devez le fermer et en créer un nouveau' ne comprenez-vous pas? 'Où veux-tu en venir?' effectivement. Est-ce que vous plaisantez? – EJP