死循环@APG中的第一个例子
初学ACE,照猫画虎,把 APG书上的例子server / client稍微改了一下。结果在server的while((bytes_received = peer.recv(buffer, sizeof(buffer)) ) != -1)这一句遇到意想不到结果。
//client
#include "ace/INET_Addr.h"
#include "ace/SOCK_Stream.h"
#include "ace/SOCK_Connector.h"
#include "ace/Log_Msg.h"
int ACE_TMAIN(int, ACE_TCHAR * [])
{
ACE_INET_Addr srvr(50000, ACE_LOCALHOST);
ACE_SOCK_Connector connector;
ACE_SOCK_Stream peer;
if (-1 == connector.connect(peer, srvr))
{
ACE_ERROR_RETURN((LM_ERROR, ACE_TEXT("%p\n"), ACE_TEXT("connect") ),1);
}
int bc;
char buf;
peer.send_n("uptime\n", 7);
bc = peer.recv(buf, sizeof(buf));
write(1, buf, bc);//输出到屏幕
peer.close();
return (0);
}
//server
#include <iostream>
#include "ace/INET_Addr.h"
#include "ace/Log_Msg.h"
#include "ace/SOCK_Acceptor.h"
#include "ace/SOCK_Stream.h"
#include "ace/Time_Value.h"
#include "ace/os_include/os_netdb.h"
using namespace std;
int ACE_TMAIN (int, ACE_TCHAR * [])
{
ACE_INET_Addr port_to_listen (50000, ACE_LOCALHOST);
ACE_SOCK_Acceptor acceptor;
if (acceptor.open(port_to_listen, 1) == -1)
{
ACE_ERROR_RETURN( (LM_ERROR, ACE_TEXT("%p\n")ACE_TEXT("acceptor.open")), 100);
}
while (1)
{
ACE_SOCK_Stream peer;
ACE_INET_Addr peer_addr;
ACE_Time_Value timeout(10, 0);
#if 0
if (acceptor.accept(peer) == -1)
{
ACE_ERROR_RETURN( (LM_ERROR, ACE_TEXT("(%P|%t) Failed to accept client connection\n")), 100);
}
#endif
if (acceptor.accept(peer, &peer_addr, &timeout, 0) == -1)
{
if (ACE_OS::last_error() == EINTR)
{
ACE_DEBUG((LM_DEBUG, ACE_TEXT("(%P|%t) Interrupted while waiting for connection\n")));
}
else if (ACE_OS::last_error() == ETIMEDOUT)
{
ACE_DEBUG((LM_DEBUG, ACE_TEXT("(%P|%t) Timeout while waiting for connection\n")));
}
}
else
{
ACE_TCHAR peer_name;
peer_addr.addr_to_string(peer_name, MAXHOSTNAMELEN);
ACE_DEBUG((LM_DEBUG, ACE_TEXT("(%P|%t) Connection from %s \n"), peer_name));
char buffer;
ssize_t bytes_received;
while( (bytes_received = peer.recv(buffer, sizeof(buffer)) ) != -1) //此处有个死循环
{
ACE_DEBUG((LM_DEBUG, ACE_TEXT("%s \n"), buffer));
peer.send_n (buffer, bytes_received);//原样返回给客户端
ACE_OS::sleep(20);
}
peer.close();
ACE_DEBUG((LM_DEBUG, ACE_TEXT("peer.close\n")));
}
}
return (0);
}
不关buffer的事。我把上面的while语句中的 != -1改成 >0就不再死循环了。
另外请教大家一个问题,我在本机收发(Client发,Server收),同时运行。我发现server端显示的端口号一直在递增,这是什么原因呢?难道我没有及时地关闭不用的连接?
页:
[1]