gpt4 book ai didi

c - 套接字编程 connect() 在我第二次运行循环时失败

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

好吧,我正在尝试在 for 循环中运行服务器端和客户端。我第一次运行它时,它运行良好,但第二次连接失败或卡在 accept() 处。这是我的代码:

客户端代码:

for(i=0;i<2;i++)
{
if( connect(sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0)
{
printf("\nError : Connect Failed\n");
return 1;
}

//***************Writing_I***************
memset(recvBuff, '0',sizeof(recvBuff));
ticks = time(NULL);
snprintf(recvBuff, sizeof(recvBuff), "%.24s\r\n", ctime(&ticks));
if((n = send(sockfd, recvBuff, strlen(recvBuff), 0))<0)
{
printf("Error : send operation failed\n");
}

//***************Reading_I***************
memset(recvBuff, '0', sizeof(recvBuff));
n= recv(sockfd, recvBuff, sizeof(recvBuff)-1, 0);
{
printf("bytes read: %d\n", n);
recvBuff[n] = '\0';
printf("Data: %s\n",recvBuff);
}
if(n < 0)
{
printf("\n Read error \n");
}
}
close(sockfd);

服务器代码:

if((connfd = accept(listenfd, (struct sockaddr*)NULL, NULL))>=0)
{
for(i=0;i<2;i++)
{
fd= open("/home/t/Desktop/CS II/A4/test.txt", O_RDONLY);
//***************Reading***************
memset(sendBuff, '0', sizeof(sendBuff));
count = recv(connfd, sendBuff, sizeof(sendBuff)-1, 0);
{
printf("bytes read: %d\n", count);
sendBuff[count] = '\0';
printf("Data: %s\n",sendBuff);
}
if(count < 0)
{
printf("Read error \n");
}

//***************Writing***************
ticks = time(NULL);
memset(sendBuff, '0', sizeof(sendBuff));
printf("Reading from file\n");
if((noOfBytesRd= read(fd, sendBuff, sizeof(sendBuff)-1))<0)
printf("\n Error : read operation failed\n");
sendBuff[noOfBytesRd]='\0';
if((count = send(connfd, sendBuff, strlen(sendBuff), 0))<0)
printf("\n Error : wtite operation failed\n");
}
close(connfd);
}

最佳答案

套接字在其生命周期中只能连接一次。您应该为每个要建立的连接创建一个单独的套接字,并在完成连接后关闭它。

关于c - 套接字编程 connect() 在我第二次运行循环时失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13557705/

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