【发布时间】:2014-04-10 12:26:05
【问题描述】:
我正在尝试使用 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()") ;
}
}
【问题讨论】:
标签: c sockets tcp infinite-loop