客户端套接字连接问题

client socket connection issue

您好,我正在尝试编写一个将尝试连接远程服务器的客户端应用程序。如果无法连接到服务器,它将在 5 秒后重试。如果套接字以某种方式关闭,它将再次尝试连接。

我收到类似 connect: Transport endpoint is already connected

的错误

可能是什么问题?

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

一旦您尝试连接某个套接字,即使它失败了,您也无法重新连接它。您必须关闭它并创建一个新的。