我正在尝试使用C。
通过Tcp连接发送数据我能够正确发送数据,但是当我关闭客户端应用程序(CTRL-C)时,服务器端的循环无限运行。
任何人都能解释一下我做错了什么吗?我该怎么做才能防止它?
//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()") ;
}
}
答案 0 :(得分:3)
您的服务器代码在2个循环中运行:外部服务器代码等待更多连接,并且只要您有连接,它就会继续运行。
目前没有理由终止其中一个。如果要终止内部值,则还应检查结果值是否为== 0
,这意味着连接结束。
即使你做了
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);
}
你的外循环继续运行。