[英]Why does the server enter an infinite loop while closing client side connection
I am trying to send data through a Tcp connection using C. 我正在尝试使用C通过Tcp连接发送数据。
I am able to send data properly , but when I close the client side application (CTRL-C), the loop in the server side runs infinitely. 我能够正确发送数据,但是当我关闭客户端应用程序(CTRL-C)时,服务器端的循环将无限运行。
Can anyone explain me what I am doing wrong ? 谁能解释我做错了什么? What can I do to prevent it?
我该如何预防?
//Server-Side code.
while (TRUE)
{
accepted_socket = accept(connection_socket, (struct sockaddr*)0, 0) ;
if(accepted_socket < 0 )
{
perror("accept function in main() ") ;
close(connection_socket) ;
exit(1) ;
}
do
{
int recieved_bytes = recv(accepted_socket, &buff,1, 0) ; // it will store the recieved characters inside the buff.
if(recieved_bytes < 0 )
{
perror("Error occurred ! Recieved bytes less than zero. in mainloop.") ;
}
printf("%c", buff) ;
}
while(buff!= ' ') ; // This loop runs infinitely.
}
//Client Side-Code
char c = 'c' ;
do
{
c = getchar() ;
if(send(*connection_socket, &c, 1, 0) < 1 )
{
if(errno == ECONNRESET)
{
fprintf(stderr, "Your message couldn't be sent, since connection was reset by the server.\n") ;
exit(1) ;
}
perror("Not all bytes sent in send() in main()") ;
}
}
Your server code runs in 2 loops: the outer one waits for more connections, and as soon as you have a connection, it goes on running. 您的服务器代码在2个循环中运行:外部的代码等待更多的连接,一旦建立连接,它就会继续运行。
There is currently no reason to terminate one of them. 当前没有理由终止其中之一。 If you want to terminate the inner one, you should additionally check for the result value being
== 0
, meaning the end of the connection. 如果要终止内部连接,则应另外检查结果值
== 0
,表示连接结束。
Even if you do 即使你这样做
while (TRUE)
{
accepted_socket = accept(connection_socket, (struct sockaddr*)0, 0);
if (accepted_socket < 0)
{
perror("accept function in main() ");
close(connection_socket);
exit(1);
}
// here starts the loop for the accepted_socket:
do
{
int recieved_bytes = recv(accepted_socket, &buff,1, 0); // it will store the recieved characters inside the buff.
if(recieved_bytes < 0)
{
perror("recv");
}
size_t i;
for (i=0; i < received_bytes; i++) printf("%c", buff[i]);
} while(received_bytes != 0);
}
your outer loop goes on running. 你的外循环继续运行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.