2017-07-28 222 views
0

嗨我想寫一個客戶端應用程序,它將嘗試連接遠程服務器。如果無法連接到服務器,則會在5秒後再次嘗試。如果套接字以某種方式關閉,它將嘗試再次連接。客戶端套接字連接問題

我發現了一個錯誤,如連接:傳輸端點已經連接

可能是什麼問題呢?

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

回答

0

即使失敗,您甚至可以在嘗試連接之前重新連接套接字。你必須關閉它並創建一個新的。

+0

那麼,你的觀點是什麼?我應該在我的代碼中做什麼? – voyvoda

+0

任何人都可以幫我嗎? – voyvoda

+0

@voyvoda'你必須關閉它並創建一個新的'的部分,你不明白嗎? '你想說啥?'確實。你在開玩笑嗎? – EJP