gpt4 book ai didi

c - 连续运行服务器套接字

转载 作者:行者123 更新时间:2023-11-30 17:22:58 26 4
gpt4 key购买 nike

我已经编写了使用 TCP 套接字在服务器和客户端之间建立连接的代码。我在断开客户端连接时遇到了问题。我希望服务器端持续运行,等待下一个客户端,即使当前客户端关闭。我的客户端代码:

int main(int argc, char *argv[])
{
int sockfd = 0, n = 0,c;
char recvBuff[1024];
struct sockaddr_in serv_addr;
if(argc != 2)
{
printf("\n Usage: %s <ip of server> \n",argv[0]);
return 1;
}

memset(recvBuff, '0',sizeof(recvBuff));
if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
printf("\n Error : Could not create socket \n");
return 1;
}

memset(&serv_addr, '0', sizeof(serv_addr));

serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(6006);

if(inet_pton(AF_INET, argv[1], &serv_addr.sin_addr)<=0)
{
printf("\n inet_pton error occured\n");
return 1;
}

if( connect(sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0)
{
printf("\n Error : Connect Failed \n");
return 1;
}
while(1)
{
printf("\n 1 to read \n");
printf("\n 2 to disconnect \n");
printf("\n 3 to exit \n");
scanf("%d",&c);
switch(c)
{
case 1:
printf("\n Inside case 1 \n");
if((n=send(sockfd,&c,sizeof(c),0))>0)
printf("\n Sent \n");
n = recv(sockfd, recvBuff, sizeof(recvBuff)-1,0);
recvBuff[n] = 0;
if(fputs(recvBuff, stdout) == EOF)
{
printf("\n Error : Fputs error\n");
}
break;
case 2:
close(sockfd);//to close only client not server
case 3:
close(sockfd);
exit(1);



}
}

}

服务器端代码:

int main(int argc, char *argv[])
{
int listenfd = 0, connfd = 0,info,n;
struct sockaddr_in serv_addr;

char sendBuff[1025];
time_t ticks;
listenfd = socket(AF_INET, SOCK_STREAM, 0);
memset(&serv_addr, '0', sizeof(serv_addr));
memset(sendBuff, '0', sizeof(sendBuff));

serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
serv_addr.sin_port = htons(6006);

bind(listenfd, (struct sockaddr*)&serv_addr, sizeof(serv_addr));

listen(listenfd, 10);

while(1)
{
connfd = accept(listenfd, (struct sockaddr*)NULL, NULL);
printf("\n Accepted \n");
while(1)
{
printf("\n Inside while \n");
if((n=recv(connfd,&info,sizeof(info),0))>0)
printf("\n received \n");
switch(info)
{
case 1:
ticks = time(NULL);
snprintf(sendBuff, sizeof(sendBuff), "%.24s\r\n", ctime(&ticks));
send(connfd, sendBuff, strlen(sendBuff),0);
break;
}
}
close(connfd);


}

}

为我提供在服务器运行时单独断开客户端连接的解决方案(服务器等待下一个客户端连接)。即使我在情况 2 中使用 return 0 它也不起作用。请帮助我。提前致谢

最佳答案

else if(n == 0)
{
printf("client disconnected\n");
close(connfd);
break;
}

在服务器程序旁边添加上述代码

if((n=recv(connfd,&info,sizeof(info),0))>0)
printf("\n received \n");

问题是当你的客户端要断开连接时,你需要发送一些 api 来关闭客户端连接。

如果客户端已正常断开连接,则上述行将自动关闭该客户端。

然后在 snprintf(sendBuff, sizeof(sendBuff), "%.24s\r\n", ctime(&ticks)); 中发出警告。

关于c - 连续运行服务器套接字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27815537/

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