五年前写的C++代码,好久没有用C++了,生疏了。

[复制链接]
1557|1
 楼主| keer_zu 发表于 2022-1-7 16:18 | 显示全部楼层 |阅读模式


一个通信程序的会话管理部分:

  1. #include <iostream>
  2. #include <memory>
  3. #include "InterfaceApiImp.h"
  4. #include "Error.h"

  5. #include "json/json.h"

  6. #include <log4cxx/logger.h>
  7. #include <log4cxx/logstring.h>
  8. #include <log4cxx/propertyconfigurator.h>

  9. #include "Log4cxxWrapper.h"



  10. using namespace log4cxx;
  11. extern LoggerPtr g_logger;

  12. using namespace std;


  13. void SessionImp::ProcessFrame(const char *buf, int length)
  14. {
  15.         int i,len = length,count = 0;
  16.         string newFrame;
  17.         int pos=0;
  18.         len =0;

  19.         LoggerWrapper dsLog= LoggerWrapper::GetInstance();
  20.        
  21.        
  22.         if(buf == NULL){
  23.                 dsLog.Log(true,LOGGER_ERROR,"buf == NULL , [%s][%s][%d]\n",__FILE__,__PRETTY_FUNCTION__,__LINE__);
  24.         }

  25.    
  26.         for(i=0;i<length;i++){
  27.                 if(buf[i] == '\0'){
  28.                         len = i-pos;
  29.                         pos = i;
  30.                         newFrame.clear();
  31.                         newFrame.assign(m_rdBuffer.begin(),m_rdBuffer.end());
  32.                         len += m_rdBuffer.size();

  33.                         if(len>1){
  34.                                 OnFrame(newFrame);
  35.                                 m_rdBuffer.clear();
  36.                         }
  37.                 } else {
  38.                         m_rdBuffer.push_back(buf[i]);
  39.                 }        
  40.         }

  41.         return;
  42. }

  43. void SessionImp::SetConnection(Connection * conn)
  44. {
  45.         LoggerWrapper& dsLog = LoggerWrapper::GetInstance();
  46.        
  47.        
  48.         if(conn == NULL){
  49.                 dsLog.Log(true,LOGGER_ERROR,"%s:SessionImp::%s:%d  error param",__FILE__,__PRETTY_FUNCTION__,__LINE__);
  50.                 return;
  51.         }
  52.        
  53.         m_connection = conn;
  54. }



  55. int SessionImp::SendMessage(string &str)
  56. {
  57.         int ret;
  58.         LoggerWrapper& dsLog = LoggerWrapper::GetInstance();
  59.        
  60.         str =str+'\0';
  61.         if(m_connection != NULL){cout << "==================== ts cmd: " << str << endl;
  62.                 ret = m_connection->Send(str.data(),str.length());

  63.                 if(ret < 0){
  64.                         dsLog.Log(true,LOGGER_ERROR,"%s:SessionImp::%s:%d",__FILE__,__PRETTY_FUNCTION__,__LINE__);
  65.                 }
  66.                
  67.                 return ret;
  68.         }

  69.         return -1;
  70. }


  71. void SessionImp::ShowReadBuf()
  72. {
  73.         vector<char>::iterator iter;
  74.         for (iter = m_rdBuffer.begin(); iter != m_rdBuffer.end(); iter++){
  75.                 cout << (*iter);
  76.         }

  77.         cout << endl;
  78. }





  79. TsSessionImp::TsSessionImp(/*ITsSessionUser *sessionUser,*/TsSession *tssession)
  80. {
  81.         //m_sessionUser = sessionUser;
  82.         m_tssession = tssession;
  83.         m_sessionType = SESSION_TS;
  84. }

  85. //void TsSessionImp::SetSessionUser(ITsSessionUser *sessionUser)
  86. //{
  87.         //m_sessionUser = sessionUser;
  88. //}



  89. void TsSessionImp::Close()
  90. {
  91.         // close connect
  92.         struct TsSessionInfo *tsSessionInfo;
  93.         list<struct TsSessionInfo*>::iterator tlit;

  94.         SessionManagerImp& smi =  SessionManagerImp::GetInstance();
  95.        
  96.         m_connection->Close();

  97.         if (this->m_connection){
  98.                 delete this->m_connection;
  99.                 this->m_connection = NULL;
  100.         }

  101.         for (tlit = smi.m_tsSessionList.begin();tlit != smi.m_tsSessionList.end();tlit ++) {
  102.                 tsSessionInfo = *tlit;
  103.                 if(tsSessionInfo != NULL){
  104.                         if(tsSessionInfo->session == this->m_tssession){
  105.                                
  106.                                 smi.m_tsSessionList.erase(tlit);   

  107.                                 delete tsSessionInfo;
  108.                                
  109.                                 break;
  110.                         }
  111.                 }
  112.         }

  113.         delete this;
  114. }


  115. void TsSessionImp::OnData(const char *buf, int length, Connection *conn)
  116. {
  117.         ProcessFrame(buf,length);
  118. }

  119.         // called when user can write data to network.
  120. void TsSessionImp::OnWrite(Connection *conn)
  121. {

  122. }
  123.         // called when the connection is broken, if user call Connection::Close(), //&&&
  124.         // will not get this callback.
  125. void TsSessionImp::OnDisconnect(int reason, Connection *conn)
  126. {
  127.         SessionManagerImp& smi =  SessionManagerImp::GetInstance();

  128.         if(this->m_tssession != NULL)
  129.                 smi.OnSessionClose(*this->m_tssession);
  130.        
  131.         Close();
  132. }

  133. bool TsSessionImp::OnFrame(string &frame)
  134. {
  135.         struct TsSessionInfo *tsSessionInfo;
  136.         list<struct TsSessionInfo*>::iterator it;
  137.         //ITsSessionUser* tsSessionUser;
  138.         Json::Value  value;  
  139.         LoggerWrapper& dsLog = LoggerWrapper::GetInstance();
  140.         SessionManagerImp& smi =  SessionManagerImp::GetInstance();

  141.         std::auto_ptr<Json::Reader> pJsonParser(new Json::Reader(Json::Features::strictMode()));

  142.         ITsNewFrame* itsu;
  143.        

  144.         if(!pJsonParser->parse(frame,value)){
  145.                 dsLog.Log(true,LOGGER_ERROR,"message Decode error! %s : %s : %d",__FILE__,__PRETTY_FUNCTION__,__LINE__);
  146.                 return false;
  147.         }

  148.         if(value["type"].isNull() ||  !value["type"].isString()){
  149.                 dsLog.Log(true,LOGGER_ERROR,"message Decode error! %s : %s : %d",__FILE__,__PRETTY_FUNCTION__,__LINE__);
  150.                 return false;
  151.         }


  152.         if(value["type"] == "LinkResponse"){
  153.                 for(it = smi.m_tsSessionList.begin();it != smi.m_tsSessionList.end();it ++) {//printf("[url=home.php?mod=space&uid=1353124]@@@@@@@@@@@[/url] leng:%d     0x%x     (%d)\n",smi.m_tsSessionList.size(),it,__LINE__);
  154.                         tsSessionInfo = *it;
  155.                         if(tsSessionInfo != NULL){
  156.                                 if(tsSessionInfo->session == this->m_tssession){
  157.                                         tsSessionInfo->timeOut = 0;
  158.                                         break;
  159.                                 }
  160.                         }
  161.                 }
  162.         } else {
  163.                 itsu= smi.GetTsNewFrame();
  164.                 if(itsu == NULL){
  165.                         dsLog.Log(true,LOGGER_ERROR,"%s:%s:%d   smi.GetSessionUser() == NULL\n",__FILE__,__PRETTY_FUNCTION__,__LINE__);
  166.                         return false;
  167.                 }
  168.                 itsu->OnNewFrame(this->m_tssession,frame);
  169.         }

  170.         return true;
  171. }

  172. /////////////////////// ts client session ///////////////////////

  173. void TsClientSessionImp::Close()
  174. {

  175. }

  176. void TsClientSessionImp::OnData(const char *buf, int length, Connection *conn)
  177. {

  178. }

  179.         // called when user can write data to network.
  180. void TsClientSessionImp::OnWrite(Connection *conn)
  181. {

  182. }
  183.         // called when the connection is broken, if user call Connection::Close(), //&&&
  184.         // will not get this callback.
  185. void TsClientSessionImp::OnDisconnect(int reason, Connection *conn)
  186. {

  187. }

  188. bool TsClientSessionImp::OnFrame(string &frame)
  189. {
  190. }
  191. /////////////////// /// app server session /////////////////////




  192. void AppServerSessionImp::Close()
  193. {
  194.         m_connection->Close();

  195.         if (this->m_connection){
  196.                 delete this->m_connection;
  197.                 this->m_connection = NULL;
  198.         }

  199.         delete this;
  200. }

  201. void AppServerSessionImp::OnData(const char *buf, int length, Connection *conn)
  202. {
  203.         //printf("++++++++++++++++++++++++++++++++++: \n%s\n",buf);
  204.     LoggerWrapper dsLog= LoggerWrapper::GetInstance();
  205.        
  206.         dsLog.Log(true,LOGGER_DEBUG,"\n\n ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n MSG From App:\n%s\n",buf);
  207.        
  208.         ProcessFrame(buf,length);
  209. }

  210. void AppServerSessionImp::OnWrite(Connection *conn)
  211. {

  212. }

  213. void AppServerSessionImp::OnDisconnect(int reason, Connection *conn)
  214. {
  215.         struct TsSessionInfo *tsSessionInfo;
  216.         list<struct TsSessionInfo*>::iterator tlit;
  217.        
  218.         SessionManagerImp& smi =  SessionManagerImp::GetInstance();
  219.         smi.OnSessionClose(*this);

  220.         Close();
  221. }

  222. bool AppServerSessionImp::OnFrame(string &frame)
  223. {

  224.         LoggerWrapper& dsLog = LoggerWrapper::GetInstance();

  225.         SessionManagerImp& smi =  SessionManagerImp::GetInstance();

  226.         IAppNewFrame* iael = smi.GetAppNewFrame();
  227.         if(iael == NULL){
  228.                 dsLog.Log(true,LOGGER_ERROR,"GetAppEventListener error! %s : %s : %d",__FILE__,__PRETTY_FUNCTION__,__LINE__);
  229.                 return false;
  230.         }

  231.         iael->OnNewFrame(this->m_session,frame);

  232.         return true;
  233. }


  234. //////////////////////// app client session ///////////////////


  235. void AppClientSessionImp::Close()
  236. {
  237.         if(m_connection != NULL)
  238.                 m_connection->Close();

  239.         if (this->m_connection){
  240.                 delete this->m_connection;
  241.                 this->m_connection = NULL;
  242.         }

  243.         delete this;
  244. }

  245. void AppClientSessionImp::OnData(const char *buf, int length, Connection *conn)
  246. {
  247.        
  248.         ProcessFrame(buf,length);
  249.        
  250. }

  251. void AppClientSessionImp::OnWrite(Connection *conn)
  252. {

  253. }

  254. void AppClientSessionImp::OnDisconnect(int reason, Connection *conn)
  255. {

  256.         SessionManagerImp& smi =  SessionManagerImp::GetInstance();
  257.         smi.OnSessionClose(*this);

  258.         Close();
  259. }

  260. bool AppClientSessionImp::OnFrame(string &frame)
  261. {
  262.         Json::Value  value;  
  263.         LoggerWrapper& dsLog = LoggerWrapper::GetInstance();
  264.         SessionManagerImp& smi =  SessionManagerImp::GetInstance();

  265.         std::auto_ptr<Json::Reader> pJsonParser(new Json::Reader(Json::Features::strictMode()));
  266.        

  267.         if(!pJsonParser->parse(frame,value)){
  268.                 dsLog.Log(true,LOGGER_ERROR,"message Decode error! %s : %s : %d",__FILE__,__PRETTY_FUNCTION__,__LINE__);
  269.                 return false;
  270.         }

  271.         if(value["command"].isNull() ||  !value["command"].isString()){
  272.                 dsLog.Log(true,LOGGER_ERROR,"message Decode error! %s : %s : %d",__FILE__,__PRETTY_FUNCTION__,__LINE__);
  273.                 return false;
  274.         }


  275.         if(value["command"] == "response"){
  276.                 cout << "app client OnDisconnect from(OnFrame) "  << endl;
  277.                 smi.OnSessionClose(*this);

  278.                 Close();
  279.         } else {
  280.                 dsLog.Log(true,LOGGER_ERROR,"this message may be not a AppClientSession message! %s : %s : %d",__FILE__,__PRETTY_FUNCTION__,__LINE__);
  281.                 return false;
  282.         }


  283.         return true;
  284. }






 楼主| keer_zu 发表于 2022-1-7 16:19 | 显示全部楼层
  1. #include <iostream>
  2. #include "InterfaceApiImp.h"
  3. #include "ConfigManager.h"
  4. #include "Log4cxxWrapper.h"
  5. #include "DataShow.h"
  6. #include "json/json.h"
  7. #include <execinfo.h>
  8. #include <string.h>
  9. #include "AppResultSubmit.h"



  10. using namespace cdy;



  11. SessionManagerImp::SessionManagerImp(/*SessionManager &wrapper*/)
  12.         //:m_appEventListener(NULL)
  13.         //,m_sessionUser(NULL)
  14.         :m_idleConnectionChecker(-1)
  15.         ,m_connectionTimeout(-1)
  16.         //,m_timerHandler(NULL)
  17.         ,m_dataShow(NULL)
  18. {
  19.        
  20.         struct timeval tv1={8, 0};
  21.         m_idleConnectionChecker = EventLooper::GetInstance().ScheduleTimer(&tv1, TF_FIRE_PERIODICALLY, this);


  22.         struct timeval tv2={1, 0};
  23.         m_connectionTimeout = EventLooper::GetInstance().ScheduleTimer(&tv2, TF_FIRE_PERIODICALLY, this);

  24.        
  25. }

  26. SessionManagerImp::~SessionManagerImp()
  27. {
  28.         if(m_appListener){
  29.                 m_appListener->Stop();
  30.                 delete  m_appListener;
  31.         }

  32.         if(m_tsListener){
  33.                 m_tsListener->Stop();
  34.                 delete m_tsListener;
  35.         }

  36.         EventLooper::GetInstance().CancelTimer(m_idleConnectionChecker);
  37.         EventLooper::GetInstance().CancelTimer(m_connectionTimeout);
  38. }

  39. TimerID SessionManagerImp::NewTimer(unsigned int dwInterval,TimerHandler pTimerHander )
  40. {
  41.         TimerID timerForApp;
  42.         struct timeval tv={dwInterval, 0};
  43.        
  44.         timerForApp = EventLooper::GetInstance().ScheduleTimer(&tv, TF_FIRE_PERIODICALLY, this);

  45.         m_timerMap[timerForApp] = pTimerHander;

  46.         printf("timerID: %d     %s:%d\n",timerForApp,__FUNCTION__,__LINE__);
  47.         //if(m_timerHandler == NULL)
  48.         //        m_timerHandler = pTimerHander;
  49.         return timerForApp;
  50. }
  51.        
  52. void SessionManagerImp::KillTimer(TimerID id)
  53. {
  54.         EventLooper::GetInstance().CancelTimer(id);

  55.         map<TimerID,TimerHandler>::iterator iTimer = m_timerMap.find(id);
  56.         if(iTimer !=  m_timerMap.end())
  57.                 m_timerMap.erase(iTimer);
  58.         //if(m_timerHandler != NULL)
  59.         //        m_timerHandler = NULL;
  60. }


  61. SessionManagerImp& SessionManagerImp::GetInstance()
  62. {
  63.         static  SessionManagerImp instance_;
  64.         return instance_;

  65. }

  66. bool SessionManagerImp::StartListenForAppServer(IAppNewFrame &appNewFrame)
  67. {
  68.         LoggerWrapper &loggerUser = LoggerWrapper::GetInstance();
  69.         short port;
  70.         //IAppEventListener listener;
  71.        
  72.         //m_appEventListener = &listener;

  73.        
  74.         m_appNewFrame = &appNewFrame;
  75.         m_appResultSubmit = &DocAppResultSubmit::GetInstance();//&appResultSubmit;
  76.         m_appResultSubmit->add(&VideoAppResultSubmit::GetInstance());
  77.         m_appResultSubmit->add(&DpptAppResultSubmit::GetInstance());
  78.         m_appResultSubmit->add(&NoUseTsAppResultSubmit::GetInstance());

  79.        

  80.         const string& addr = ConfigManager::GetIp();//appInfo.GetAppListenIp();
  81.         port =  (short)ConfigManager::GetAppPort();//(short)appInfo.GetAppListenPort();

  82.         m_appListener = new  Acceptor(addr, port,this);
  83.        
  84.         return m_appListener->StartListen() == 0;
  85. }


  86. bool SessionManagerImp::StartListenForTS(ITsNewFrame &tsNewFrame,ITsServerLeave &tsServerLeave)
  87. {
  88.         m_tsNewFrame = &tsNewFrame;

  89.         m_tsServerLeave = &tsServerLeave;
  90.        
  91.         m_tsListener = new  Acceptor(ConfigManager::GetIp(), (short)ConfigManager::GetTsPort(),this);
  92.        
  93.        
  94.         return m_tsListener->StartListen() == 0;
  95. }



  96. bool SessionManagerImp::DestoryConnectToServer(string ip,unsigned int port)
  97. {
  98.         map<TargetAttributeT *,IConnectorAcceptor *>::iterator it;
  99.        

  100.          for(it = m_longConnectors.begin();it != m_longConnectors.end();it ++){
  101.                  if(((TargetAttributeT *)it->first)->ip == ip && ((TargetAttributeT *)it->first)->port == port){
  102.                         // TODO: close this connection;
  103.                         if(it->first != NULL)
  104.                                 delete it->first;
  105.                        
  106.                         if(it->second)
  107.                                 delete it->second;
  108.                        
  109.                         m_longConnectors.erase(it);
  110.                        
  111.                         break;
  112.                  }
  113.         }
  114. }


  115. void SessionManagerImp::SetDataShowProvider(IDataShowProvider &dataShow)
  116. {
  117.         m_dataShow = &dataShow;
  118.         printf("####################### datashow: 0x%x\n",m_dataShow);
  119. }


  120. void print_trace(void)   
  121. {   
  122.     int i;   
  123.     const int MAX_CALLSTACK_DEPTH = 32;    /* 需要打印堆栈的最大深度 */  
  124.     void *traceback[MAX_CALLSTACK_DEPTH];  /* 用来存储调用堆栈中的地址 */  
  125.     /* 利用 addr2line 命令可以打印出一个函数地址所在的源代码位置   
  126.      * 调用格式为: addr2line -f -e /tmp/a.out 0x400618  
  127.      * 使用前,源代码编译时要加上 -rdynamic -g 选项  
  128.      */  
  129.     char cmd[512] = "addr2line -f -e ";   
  130.     char *prog = cmd + strlen(cmd);   
  131.     /* 得到当前可执行程序的路径和文件名 */  
  132.     int r = readlink("/proc/self/exe",prog,sizeof(cmd)-(prog-cmd)-1);   
  133.     /* popen会fork出一个子进程来调用/bin/sh, 并执行cmd字符串中的命令,  
  134.      * 同时,会创建一个管道,由于参数是'w', 管道将与标准输入相连接,  
  135.      * 并返回一个FILE的指针fp指向所创建的管道,以后只要用fp往管理里写任何内容,  
  136.      * 内容都会被送往到标准输入,  
  137.      * 在下面的代码中,会将调用堆栈中的函数地址写入管道中,  
  138.      * addr2line程序会从标准输入中得到该函数地址,然后根据地址打印出源代码位置和函数名。  
  139.      */  
  140.     FILE *fp = popen(cmd, "w");   
  141.     /* 得到当前调用堆栈中的所有函数地址,放到traceback数组中 */  
  142.     int depth = backtrace(traceback, MAX_CALLSTACK_DEPTH);   
  143.     for (i = 0; i < depth; i++)   
  144.     {   
  145.         /* 得到调用堆栈中的函数的地址,然后将地址发送给 addr2line */  
  146.         fprintf(fp, "%p\n", traceback[i]);   
  147.         /* addr2line 命令在收到地址后,会将函数地址所在的源代码位置打印到标准输出 */  
  148.     }   
  149.     fclose(fp);   
  150. }



  151. void SessionManagerImp::SendAppMessage(const string addr,const unsigned int port,const string msg,void* pTaskMessage)
  152. {//连接失败后尝试三次间隔时间暂定5分钟

  153.         static unsigned int ConnectTimes = 0;
  154.         Connector *connector=NULL;
  155.         static unsigned int connectErrorTimes = 0;

  156.         struct ConnectorInfo *connectorInfo;

  157.         LoggerWrapper& dsLog = LoggerWrapper::GetInstance();

  158.         if(addr == "" || msg == "" || port < 0){
  159.                 printf("addr: %s           msg: %s     port:%d\n",addr.c_str(),msg.c_str(),port);
  160. //                print_trace();
  161.                 dsLog.Log(true,LOGGER_ERROR," parameter error! line:%d\n",__LINE__);
  162.                 return;
  163.         }
  164.        
  165.         if (!connector)
  166.                 connector = new Connector(addr, port, this);

  167. try_connect:
  168.        
  169.         if (connector->Connect(300) == 0){
  170.                 connectorInfo = new struct ConnectorInfo;//(struct ConnectorInfo *)malloc(sizeof(struct ConnectorInfo));
  171.                 if(connectorInfo == NULL){
  172.                         dsLog.Log(true,LOGGER_ERROR," new struct ConnectorInfo error! \n");
  173.                         return;
  174.                 }
  175.                
  176.                 connectorInfo->msg = msg;
  177.                 connectorInfo->re_connect_times = 0;
  178.                 connectorInfo->pTaskMessage = pTaskMessage;
  179.                 m_connectors[connector] = connectorInfo;

  180.                 connectErrorTimes = 0;
  181.                
  182.         } else {
  183.        
  184.                 delete connector;

  185.                 connectErrorTimes ++;
  186.                
  187.                 if (connectErrorTimes < 3){
  188.                         connector = new Connector(addr, port, this);
  189.                         goto try_connect;
  190.                 }

  191.                 connectErrorTimes = 0;
  192.                
  193.         }

  194.         return;

  195. }

  196. void SessionManagerImp::OnNewSession(SessionImp &session)
  197. {
  198.         list<SessionImp*>::iterator alit;
  199.        
  200.         if(session.m_sessionType == SESSION_APP_CLIENT){
  201.                
  202.         } else if(session.m_sessionType == SESSION_APP_SERVER){

  203.         }
  204. }

  205. void SessionManagerImp::OnNewSession(TsSession &session)
  206. {
  207.         list<struct TsSessionInfo*>::iterator tlit;
  208.        
  209. }




  210. void SessionManagerImp::OnSessionClose(SessionImp &session)
  211. {
  212.         LoggerWrapper& dsLog = LoggerWrapper::GetInstance();
  213.        
  214.         list<SessionImp*>::iterator alit;
  215.         SessionImp *session_imp;

  216.        
  217.         if(session.m_sessionType == SESSION_APP_CLIENT){
  218.                
  219.                 for (alit = m_appClientSessionList.begin();alit != m_appClientSessionList.end();alit ++) {
  220.                         session_imp = *alit;
  221.                         if(session_imp == &session){
  222.                                 m_appClientSessionList.erase(alit);  
  223.                                
  224.                                 break;
  225.                         }
  226.                 }
  227.                
  228.         } else if(session.m_sessionType == SESSION_APP_SERVER){
  229.                 for (alit = m_appServerSessionList.begin();alit != m_appServerSessionList.end();alit ++) {
  230.                         session_imp = *alit;
  231.                         if(session_imp == &session){
  232.                                 m_appServerSessionList.erase(alit);   
  233.                                
  234.                                 break;
  235.                         }
  236.                 }

  237.         }
  238. }

  239. void SessionManagerImp::OnSessionClose(TsSession &session)
  240. {
  241.         struct TsSessionInfo *tsSessionInfo;
  242.         list<struct TsSessionInfo*>::iterator tlit;

  243.         if(m_tsServerLeave != NULL)
  244.                 m_tsServerLeave->OnServerLeave(session);
  245.        
  246.         for (tlit = m_tsSessionList.begin();tlit != m_tsSessionList.end();tlit ++) {//printf("@@@@@@@@@@@ leng:%d     0x%x     (%d)\n",m_tsSessionList.size(),tlit,__LINE__);
  247.                 tsSessionInfo = *tlit;
  248.                 if(tsSessionInfo->session == &session){
  249.                        
  250.                         m_tsSessionList.erase(tlit);   

  251.                         delete tsSessionInfo;
  252.                        
  253.                         break;
  254.                 }
  255.         }
  256. }

  257. void SessionManagerImp::OnConnection(Connection *conn, IConnectorAcceptor *ca)
  258. {
  259.         int ret;
  260.        
  261.         TsSession *ts_session;
  262.         struct TsSessionInfo *tsSessionInfo;
  263.         //TsSessionImp *ts_session_imp;
  264.         TsSessionImp *ts_session_imp;
  265.         SessionImp *session_imp;
  266.         TsClientSession *tsClientSession;
  267.         //TsClientSessionImp *tsClientSessionImp;


  268.         map<IConnectorAcceptor*,struct ConnectorInfo *>::iterator it;

  269.         map<TargetAttributeT *,IConnectorAcceptor *>::iterator lcit;

  270.         LoggerWrapper& dsLog = LoggerWrapper::GetInstance();

  271.         if(!ca){
  272.                 return;
  273.         }

  274.         if (conn){
  275.                 if (ca->IsConnector() == false){//accepter
  276.                         if (ca == m_tsListener) {//ts

  277.                                 ts_session = new TsSession();
  278.                                 if(ts_session == NULL){
  279.                                         dsLog.Log(true,LOGGER_ERROR," new TsSession error! \n");
  280.                                         return;
  281.                                 }
  282.                                
  283.                                 conn->SetConnectionSink(ts_session->m_imp);

  284.                                 tsSessionInfo = new struct TsSessionInfo;
  285.                                 if (tsSessionInfo == NULL){
  286.                                        
  287.                                         dsLog.Log(true,LOGGER_ERROR,"malloc error!\n");
  288.                                 }

  289.                                 tsSessionInfo->session = ts_session;
  290.                                
  291.                                 ts_session_imp = (TsSessionImp *)ts_session->m_imp;
  292.                                 //ts_session_imp->SetSessionUser(this->m_sessionUser);
  293.                                 ts_session_imp->SetConnection(conn);

  294.                                 tsSessionInfo->timeOut = 0;
  295.                                
  296.                                 m_tsSessionList.push_back(tsSessionInfo);
  297.                                 OnNewSession(*ts_session);
  298.                                
  299.                         } else if (ca == m_appListener){ //app

  300.                                 session_imp = new AppServerSessionImp(conn/*,this->m_appEventListener*/);
  301.                                 if(session_imp == NULL){
  302.                                         dsLog.Log(true,LOGGER_ERROR," new AppServerSessionImp error! \n");
  303.                                         return;
  304.                                 }
  305.                                
  306.                                 conn->SetConnectionSink(session_imp);
  307.                                 session_imp->SetConnection(conn);

  308.                                 m_appServerSessionList.push_back(session_imp);
  309.                                 OnNewSession(*session_imp);
  310.                                
  311.                         } else {
  312.                                
  313.                         }
  314.                        
  315.                 } else {//connector

  316.                          for(lcit = m_longConnectors.begin();lcit != m_longConnectors.end();lcit ++){
  317.                                  if((IConnectorAcceptor *)lcit->second == ca){
  318.                                         tsClientSession = new TsClientSession();
  319.                                         if(session_imp == NULL){
  320.                                                 dsLog.Log(true,LOGGER_ERROR," new AppClientSessionImp error! \n");
  321.                                                 return;
  322.                                         }

  323.                                         //conn->SetConnectionSink(session_imp);
  324.                                         //session_imp->SetConnection(conn);
  325.                                         conn->SetConnectionSink(tsClientSession->m_imp);
  326.                                         tsClientSession->m_imp->SetConnection(conn);

  327.                                         TsClientSessionInfoT *info = new TsClientSessionInfoT;
  328.                                         info->session =tsClientSession;//->m_imp->m_session;
  329.                                         info->ip = ((TargetAttributeT *)lcit->first)->ip;
  330.                                         info->port = ((TargetAttributeT *)lcit->first)->port;
  331.                                        
  332.                                         m_tsClinetSessionList.push_back(info);
  333.                                         // TODO:OnNewSession(*session_imp);
  334.                                        
  335.                                         return;
  336.                                  }
  337.                         }

  338.                         it = m_connectors.find(ca);
  339.                         if(it != m_connectors.end()){  //

  340.                                 session_imp = new AppClientSessionImp(conn);
  341.                                 if(session_imp == NULL){
  342.                                         dsLog.Log(true,LOGGER_ERROR," new AppClientSessionImp error! \n");
  343.                                         return;
  344.                                 }
  345.                                
  346.                                 conn->SetConnectionSink(session_imp);
  347.                                 session_imp->SetConnection(conn);

  348.                                 m_appClientSessionList.push_back(session_imp);
  349.                                 OnNewSession(*session_imp);

  350.                                 if(it->second != NULL){
  351.                                         ret = session_imp->SendMessage(it->second->msg);
  352.                                         m_appResultSubmit->OnResultSubmit(ret,it->second->pTaskMessage);
  353.                                 }
  354.                                 dsLog.Log(true,LOGGER_INFO,"Send app message:%s, %s:%s:%d",it->second->msg.c_str(),__FILE__,__PRETTY_FUNCTION__,__LINE__);
  355.                                        
  356.                                 delete ca;

  357.                                 if(it->second != NULL)
  358.                                         delete it->second;
  359.                                 m_connectors.erase(it);
  360.                                
  361.                         } else {  // error ,Can not find connector
  362.                                 dsLog.Log(true,LOGGER_ERROR,"Can not find connector! :%d",__LINE__);
  363.                                 delete ca;
  364.                         }
  365.                 }
  366.         } else {   
  367.                 //Added by wwz 160424 for test
  368.                 printf("conn is NULL\n");
  369.    
  370. //                cout << "not connected, try again!" << endl;
  371.                 if (ca->IsConnector() == true){//connector
  372.                         it = m_connectors.find(ca);
  373.                         if(it == m_connectors.end()){  //This connector does not exist
  374.                                 cout << "This connector does not exist :%d" << endl;
  375.                         } else {
  376.                                 if(it->second != NULL){
  377.                                         if(it->second->re_connect_times == 0){
  378.                                                 it->second->re_connect_times = 3;    //Join the Error handling map
  379.                                         } else {
  380.                                                 if(it->second->re_connect_times == 1){  //Connection failed three times
  381.                                                         //Added by wwz 160424 for test,for connection failure
  382.                                                         printf("connection failure,send task result fail!\n");
  383.                                                         m_appResultSubmit->OnResultSubmit(ret,it->second->pTaskMessage);
  384.                                                
  385.                                                         delete ca;
  386.                                                         delete it->second;
  387.                                                         m_connectors.erase(it); //it->second
  388.                                                 } else {
  389.                                                         it->second->re_connect_times -= 1;
  390.                                                 }
  391.                                         }
  392.                                 }
  393.                         }
  394.                 }
  395.         }
  396. }


  397. void SessionManagerImp::OnTimer(TimerID tid)
  398. {
  399.         struct TsSessionInfo *tsSessionInfo;
  400.         string json;
  401.         Json::Value root;

  402.         root["type"] = "SvrLinkCheck";

  403.         map<TimerID,TimerHandler>::iterator iTimer;

  404.         //root.toStyledString();
  405.         json = root.toStyledString();
  406.        
  407.         //SvrLinkCheck svrLinkCheck;
  408.         map<IConnectorAcceptor*,struct ConnectorInfo *>::iterator mit;
  409.         list<struct TsSessionInfo *>::iterator it;
  410.         map<TargetAttributeT *,IConnectorAcceptor *>::iterator lcit;
  411.         //TsMessageBase *msg;
  412.         TsSession *tsSession;
  413.         LoggerWrapper& dsLog = LoggerWrapper::GetInstance();
  414.         Connector *connector=NULL;
  415.        
  416.         if (tid == m_connectionTimeout){
  417.                  for(mit = m_connectors.begin();mit != m_connectors.end();){
  418.                          if(mit->second != NULL){
  419.                                 if(mit->second->re_connect_times >= 1){
  420.                                         if(((Connector *)(mit->first))->Connect(300) != 0){// Remove from map directly
  421.                                                 if(mit->first != NULL)
  422.                                                         delete mit->first;
  423.                                                 delete mit->second;
  424.                                                 m_connectors.erase(mit ++);
  425.                                         } else {
  426.                                                 mit ++;
  427.                                         }
  428.                                        
  429.                                 } else {
  430.                                         mit ++;
  431.                                 }
  432.                          }
  433.             else
  434.             {
  435.                 mit ++;
  436.             }
  437.                  }

  438.                 for(lcit = m_longConnectors.begin();lcit != m_longConnectors.end();lcit ++){
  439.                         if (lcit->second == NULL){
  440.                                 if(((TargetAttributeT *)lcit->first)->reconnectInterval >= LONG_CONNECT_RETRY_INTERFAL){
  441.                                         if (!connector)
  442.                                                 connector = new Connector(((TargetAttributeT *)lcit->first)->ip,((TargetAttributeT *)lcit->first)->port, this);
  443.                                         if (connector->Connect(300) == 0){
  444.                                                 lcit->second = connector;
  445.                                         } else {
  446.                                                 ((TargetAttributeT *)lcit->first)->reconnectInterval = 0;
  447.                                         }
  448.                                 } else {
  449.                                         ((TargetAttributeT *)lcit->first)->reconnectInterval += 1;
  450.                                 }
  451.                         }
  452.                 }
  453.         } else if(tid == m_idleConnectionChecker) {
  454.                 for(it = m_tsSessionList.begin();it != m_tsSessionList.end();) {//printf("@@@@@@@@@@@ leng:%d     0x%x     (%d)\n",m_tsSessionList.size(),it,__LINE__);
  455.                        
  456.                         tsSessionInfo = *(it++);
  457.                         if(tsSessionInfo == NULL){
  458.                                 dsLog.Log(true,LOGGER_ERROR," tsSessionInfo is NUL!");
  459.                                 return;
  460.                         }
  461.                        
  462.                         tsSession = tsSessionInfo->session;
  463.                         if(tsSession == NULL){
  464.                                 dsLog.Log(true,LOGGER_ERROR," tsSession is NUL!");
  465.                                 return;
  466.                         }

  467.                         if(tsSessionInfo->timeOut == 1) {  // Timeout handling
  468.                                 dsLog.Log(true,LOGGER_DEBUG,"Timeout handling!  session:0x%x   sessionimp:0x%x\n",tsSessionInfo->session,tsSessionInfo->session->m_imp);       
  469.                                 OnSessionClose(*tsSessionInfo->session);
  470.                                 tsSession->Close();

  471.                         } else {
  472.                                        
  473.                                 tsSessionInfo->session->SendMessage(/**msg*/json);
  474.                                 tsSessionInfo->timeOut = 1;

  475.                         }
  476.                 }
  477.         //}else if(tid == m_timerForApp){
  478.         //                m_timerHandler();               
  479.         } else { //app timer handle
  480.                
  481.                 for(iTimer = m_timerMap.begin();iTimer != m_timerMap.end();++ iTimer){
  482.                         if(tid == iTimer->first){
  483.                                 ((TimerHandler)iTimer->second)();
  484.                                 break;
  485.                         }
  486.                 }
  487.         }

  488. }

  489. //IAppEventListener* SessionManagerImp::GetAppEventListener() const
  490. //{
  491. //        return m_appEventListener;
  492. //}

  493. IAppNewFrame *SessionManagerImp::GetAppNewFrame() const
  494. {

  495.         return m_appNewFrame;
  496. }


  497. //ITsSessionUser* SessionManagerImp::GetSessionUser() const
  498. //{
  499. //        return m_sessionUser;
  500. //}

  501. ITsNewFrame* SessionManagerImp::GetTsNewFrame() const
  502. {
  503.         return m_tsNewFrame;
  504. }

  505. void SessionManagerImp::ShowConnectors()
  506. {
  507.         int i;
  508.         map<IConnectorAcceptor*,struct ConnectorInfo *>::iterator mit;
  509.        
  510.         if(m_dataShow == NULL)
  511.                 return;
  512.        
  513.         m_dataShow->DataPrint("\n\n\n++++++ connectors:\n");
  514.         for(mit = m_connectors.begin(),i = 0;mit != m_connectors.end();mit ++,i ++){
  515.                 m_dataShow->DataPrint("----------------the %dth elem: \n",i);
  516.                 m_dataShow->DataPrint("connector: 0x%x\n",(Connector *)(mit->first));
  517.                 m_dataShow->DataPrint("msg: %s\n",((struct ConnectorInfo *)mit->second)->msg.data());
  518.                 m_dataShow->DataPrint("re_connect_times: %d\n",((struct ConnectorInfo *)mit->second)->re_connect_times);
  519.                 m_dataShow->DataPrint("\n\n\n");
  520.         }
  521.        
  522. }


  523. void SessionManagerImp::ShowTsSessionList()
  524. {
  525.         int i;
  526.         struct TsSessionInfo *tsSessionInfo;
  527.         list<struct TsSessionInfo *>::iterator it;
  528.        
  529.         if(m_dataShow == NULL)
  530.                 return;
  531.        
  532.         m_dataShow->DataPrint("\n\n\n++++++ ts_session_list:\n");
  533.         for(it = m_tsSessionList.begin(),i = 0;it != m_tsSessionList.end();it ++,i ++) {//printf("@@@@@@@@@@@ leng:%d     0x%x     (%d)\n",m_tsSessionList.size(),it,__LINE__);
  534.                 tsSessionInfo = *it;
  535.                 m_dataShow->DataPrint("----------------the %dth elem:  \n",i);
  536.                 m_dataShow->DataPrint("session: 0x%x\n",tsSessionInfo->session);
  537.                 m_dataShow->DataPrint("timeOut:%d\n",tsSessionInfo->timeOut);
  538.                 m_dataShow->DataPrint("\n\n\n");
  539.         }
  540. }

  541. void SessionManagerImp::ShowAppServerSessionList()
  542. {
  543.         int i;
  544.         list<SessionImp*>::iterator alit;
  545.        
  546.         if(m_dataShow == NULL)
  547.                 return;

  548.         m_dataShow->DataPrint("\n\n\n++++++ app_server_session_list:\n");
  549.         for (alit = m_appServerSessionList.begin(),i = 0;alit != m_appServerSessionList.end();alit ++,i ++) {
  550.                 m_dataShow->DataPrint("----------------the %dth elem:   \n",i);
  551.                 m_dataShow->DataPrint("session_imp: 0x%x\n",*alit);
  552.                 m_dataShow->DataPrint("\n\n\n");
  553.         }
  554.                
  555. }

  556. void SessionManagerImp::ShowAppClientSessionList()
  557. {
  558.         int i;
  559.         list<SessionImp*>::iterator alit;
  560.        
  561.         if(m_dataShow == NULL)
  562.                 return;
  563.        
  564.         m_dataShow->DataPrint("\n\n\n++++++ app_client_session_list:\n");
  565.         for (alit = m_appClientSessionList.begin();alit != m_appClientSessionList.end();alit ++,i ++) {
  566.                 m_dataShow->DataPrint("----------------the %dth elem:    \n",i);
  567.                 m_dataShow->DataPrint("session_imp: 0x%x\n",*alit);
  568.                 m_dataShow->DataPrint("\n\n\n");
  569.         }

  570. }





您需要登录后才可以回帖 登录 | 注册

本版积分规则

个人签名:qq群:49734243 Email:zukeqiang@gmail.com

1488

主题

12949

帖子

55

粉丝
快速回复 在线客服 返回列表 返回顶部