|
楼主 |
发表于 2012-10-11 23:27:58
|
显示全部楼层
本帖最后由 manlianmu 于 2012-10-12 08:55 编辑
winston 发表于 2012-10-11 16:43
能贴一些代码吗? 可以,
int Server::handle_input(ACE_HANDLE)
{
char buffer[1024]; // Insure a trailing nul
ssize_t bytes_read = 0;
bytes_read = this->peer ().recv (buffer,20);
ACE_DEBUG ((LM_DEBUG,
ACE_TEXT ("Received Message bytes_read = %d\n"),
bytes_read));
/*新增非阻塞处理新情况*/
if(bytes_read == -1)//出错
{
if(errno == EWOULDBLOCK)//非阻塞只需判断EWOULDBLOCK
{
return 0;
}
else
ACE_ERROR_RETURN ((LM_ERROR,
ACE_TEXT ("(%t) %p\n"),
ACE_TEXT ("Server::handle_input")),
-1);
}
else if (bytes_read == 0)//连接关闭,停止接收
return -1;
return 0;
}
int Server::handle_close(ACE_HANDLE handle,
ACE_Reactor_Mask mask)
{
ACE_DEBUG ((LM_INFO,
ACE_TEXT ("(%t) Server Svc_Handler closing ")
ACE_TEXT ("handle <%d,%d> with reactor mask <0x%x>.\n"),
handle,
this->get_handle (),
mask));
this->peer ().close ();
return 0;
}
int DemoAcceptor::accept_svc_handler (Server *handler)
{
int result = this->MyAcceptor::accept_svc_handler (handler);
if (result != 0)
{
if (errno != EWOULDBLOCK)
ACE_ERROR ((LM_ERROR,
ACE_TEXT ("(%t) %p\n"),
ACE_TEXT ("Unable to accept connection")));
return result;
}
ACE_DEBUG ((LM_DEBUG,
ACE_TEXT ("(%t) Accepted connection. ")
ACE_TEXT ("Stream handle: <%d>\n"),
handler->get_handle ()));
return result;
}
/*开个服务器+接收器线程工作*/
ACE_THR_FUNC_RETURN server_worker(void *p)
{
const unsigned short port = *(static_cast<unsigned short *> (p));
ACE_INET_Addr addr;
if(addr.set(port,INADDR_LOOPBACK)!=0)
{
ACE_ERROR ((LM_ERROR,
ACE_TEXT ("(%t) %p\n"),
ACE_TEXT ("server_worker - ACE_INET_Addr::set")));
return (void *) -1;
}
DemoPollReactor dp_reactor(10010);//EPOLL ,此时ET模式,//最大允许的连接数,可调整
dp_reactor.restart(1);
ACE_Reactor reactor(&dp_reactor);
DemoAcceptor server;
int flags = 0;
ACE_SET_BITS(flags,ACE_NONBLOCK);//非阻塞
if(server.open(addr,&reactor,flags)!=0)//监听
{
ACE_ERROR ((LM_ERROR,
ACE_TEXT ("(%t) %p\n"),
ACE_TEXT ("Unable to open server service handler")));
return (void *) -1;
}
if (reactor.run_reactor_event_loop () != 0)
{
ACE_ERROR ((LM_ERROR,
ACE_TEXT ("(%t) %p\n"),
ACE_TEXT ("Error when running server ")
ACE_TEXT ("reactor event loop")));
return (void *) -1;
}
ACE_DEBUG ((LM_INFO,
ACE_TEXT ("(%t) Reactor event loop finished ")
ACE_TEXT ("successfully.\n")));
return 0;
}
int ACE_TMAIN(int argc, ACE_TCHAR* argv[])
{
unsigned short port = 23234;
// Server server;
// server.open(0);
ACE_DEBUG((LM_DEBUG,"open after!\n"));
if(ACE_Thread_Manager::instance()->spawn(server_worker,&port)==-1)
ACE_ERROR_RETURN ((LM_ERROR,
ACE_TEXT ("(%t) %p\n"),
ACE_TEXT ("Unable to spawn server thread")),
-1);
if (ACE_Thread_Manager::instance ()->wait () != 0)
ACE_ERROR_RETURN ((LM_ERROR,
ACE_TEXT ("(%t) %p\n"),
ACE_TEXT ("Error waiting for threads to complete")),
-1);
return 0;
} |
|