1. 程式人生 > 其它 >基於框架的網路程式設計之NetReactor_tcp_server

基於框架的網路程式設計之NetReactor_tcp_server

2019獨角獸企業重金招聘Python工程師標準>>> hot3.png

/************************************************************************/
//Copyright2015,han_gangbiao.Allrightsreserved.
//
//[Time]:2015-7-123:11:24
//[Author]:han_gangbiao
//[Info]:NetReactor_tcp_server
/************************************************************************/

#include"stdafx.h"
#include"xsmart.h"
#include"xnet/NetReactor.h"
#include"xbase/xthread.h"
#include"xbase/xlogger.h"
#include<iostream>

XNetReactornet_reactor_obj;

classXTcpServer:publicIEventHandler
{
public:
XTcpServer(){}
virtual~XTcpServer(){}
public:
virtualinton_connect(SOCK_FDcli_fd,constchar*remote_ip,intremote_port);
virtualinton_recv_data(SOCK_FDfd,constchar*data,intlen,constchar*remote_ip,intremote_port);
virtualinton_send_ack(SOCK_FDfd,intlen);
virtualinton_close(SOCK_FDfd,interror);
private:
};

intXTcpServer::on_connect(SOCK_FDcli_fd,constchar*remote_ip,intremote_port)
{
printf("on_connectfd=%d,remote_ip[%s],remort_port[%d]\n",cli_fd,remote_ip,remote_port);
return0;
}

intXTcpServer::on_recv_data(SOCK_FDfd,constchar*data,intlen,constchar*remote_ip,intremote_port)
{
printf("%sfrom-[%s:%d]\n",data,remote_ip,remote_port);
net_reactor_obj.send(fd,data,len);
return0;
}

intXTcpServer::on_send_ack(SOCK_FDfd,intlen)
{
printf("on_send_ackfd=%d,len=%d\n",fd,len);
return0;
}

intXTcpServer::on_close(SOCK_FDfd,interror)
{
XLOG_ERROR("on_close(fd=%d,error=%d)\n",fd,error);
return0;
}

//main
intmain(intargc,char*argv[])
{
smart::XSmartLib::init();
XLOG_SET_STDERR(true);
std::cout<<smart::XSmartLib::getLibInfo()<<std::endl;

XTcpServer*tcpserver=newXTcpServer;

#ifdefOS_WIN
net_reactor_obj.init_reactor(tcpserver,XNetReactor::REACTOR_TCP_SERVER,XNetReactor::REACTOR_DEFAULT);
#else
//epoll-model
net_reactor_obj.init_reactor(tcpserver,XNetReactor::REACTOR_TCP_SERVER,XNetReactor::REACTOR_EPOLL);
#endif

net_reactor_obj.open_tcp_server("0.0.0.0",8800);

while(1)
{
SLEEP_MS(1000);
}

net_reactor_obj.uninit_reactor();
SAFE_DELETE(tcpserver);
smart::XSmartLib::unInit();
return0;
}


轉載於:https://my.oschina.net/jackhen/blog/473111