gpt4 book ai didi

linux - 客户端套接字连接问题

转载 作者:太空宇宙 更新时间:2023-11-04 04:33:07 25 4
gpt4 key购买 nike

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

最佳答案

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

关于linux - 客户端套接字连接问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45372622/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com