客户端套接字连接问题

时间:2017-07-28 11:41:52

标签: linux sockets connection

您好我正在尝试编写一个尝试连接远程服务器的客户端应用程序。如果无法连接到服务器,它将在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;
    }

1 个答案:

答案 0 :(得分:0)

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