IServerImpl.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481
  1. #include "StdAfx.h"
  2. #include "IServerImpl.h"
  3. #include <comdef.h>
  4. #include <atlbase.h>
  5. #include <strsafe.h>
  6. #include "ThreadPool.hpp"
  7. #include "ClientProcess.h"
  8. // #ifdef _DEBUG
  9. // #define new DEBUG_NEW
  10. // #endif
  11. const int AF_IPV4 = 0;
  12. const int AF_IPV6 = 1;
  13. const int SOCK_TCP = SOCK_STREAM-1;
  14. const int SOCK_UDP = SOCK_DGRAM-1;
  15. namespace ServerSocketImpl
  16. {
  17. IServerImpl* g_pServerSocket[20] = {0};
  18. IServerImpl::IServerImpl():m_nMode(AF_IPV4)
  19. ,m_nSockType(SOCK_TCP)
  20. ,m_strPort(_T("64320"))
  21. ,m_nSocketIndex(0)
  22. {
  23. m_bStopbeat = FALSE;
  24. InitializeCriticalSection( &m_csProcessData );
  25. m_SocketServer.SetInterface(this);
  26. }
  27. IServerImpl::~IServerImpl()
  28. {
  29. m_SocketServer.Terminate();
  30. DeleteCriticalSection( &m_csProcessData );
  31. }
  32. BOOL IServerImpl::Initialize()
  33. {
  34. TCHAR szIPAddr[MAX_PATH] = { 0 };
  35. CSocketHandle::GetLocalAddress(szIPAddr, MAX_PATH, AF_INET);
  36. //AppendText(_T("Local Address (IPv4): %s\r\n"), szIPAddr);
  37. CSocketHandle::GetLocalAddress(szIPAddr, MAX_PATH, AF_INET6);
  38. //AppendText(_T("Local Address (IPv6): %s\r\n"), szIPAddr);
  39. return TRUE;
  40. }
  41. void IServerImpl::Start(IN LPCTSTR strPort,IN const int &nMode)
  42. {
  43. m_nMode = nMode;
  44. int nFamily = (m_nMode == AF_IPV4) ? AF_INET : AF_INET6;
  45. if (!m_SocketServer.StartServer(NULL, strPort, nFamily, (m_nSockType+1)))
  46. {
  47. //OutputDebugString(_T("\n连接服务器失败!\n"));
  48. AfxMessageBox(_T("Failed to start server."), NULL, MB_ICONSTOP);
  49. return;
  50. }
  51. CClientProcess::GetInstance()->StartMsgWork();
  52. //SyncControls();
  53. }
  54. void IServerImpl::Stop()
  55. {
  56. if(m_hRunObject)
  57. SetEvent(m_hRunObject);
  58. if( m_hClearInvalidateSocketThread )
  59. {
  60. if (WaitForSingleObject(m_hClearInvalidateSocketThread,INFINITE) != WAIT_FAILED)
  61. {
  62. CloseHandle(m_hClearInvalidateSocketThread);
  63. m_hClearInvalidateSocketThread = NULL;
  64. }
  65. }
  66. if ( m_hRunObject )
  67. CloseHandle( m_hRunObject );
  68. m_hRunObject = NULL;
  69. m_SocketServer.Terminate();
  70. //SyncControls();
  71. }
  72. void IServerImpl::Send()
  73. {
  74. if ( m_SocketServer.IsOpen() )
  75. {
  76. CString strMsg;
  77. //m_ctlMessage.GetWindowText( strMsg );
  78. if ( strMsg.IsEmpty() )
  79. {
  80. //AppendText( _T("Please enter the message to send.\r\n") );
  81. return;
  82. }
  83. USES_CONVERSION;
  84. if (m_nSockType == SOCK_TCP)
  85. {
  86. const LPBYTE lpbData = (const LPBYTE)(T2CA(strMsg));
  87. // unsafe access to Socket list!
  88. #ifdef SOCKHANDLE_USE_OVERLAPPED
  89. const SocketContextList& sl = m_SocketServer.GetSocketList();
  90. for(SocketContextList::const_iterator citer = sl.begin(); citer != sl.end(); ++citer)
  91. #else
  92. const SocketList& sl = m_SocketServer.GetSocketList();
  93. for(SocketList::const_iterator citer = sl.begin(); citer != sl.end(); ++citer)
  94. #endif
  95. {
  96. CSocketHandle sockHandle;
  97. sockHandle.Attach( (*citer) );
  98. sockHandle.Write(lpbData, strMsg.GetLength(), NULL);
  99. sockHandle.Detach();
  100. }
  101. }
  102. else
  103. {
  104. SockAddrIn servAddr, sockAddr;
  105. m_SocketServer->GetSockName(servAddr);
  106. GetDestination(sockAddr);
  107. if ( servAddr != sockAddr )
  108. {
  109. m_SocketServer.Write((const LPBYTE)(T2CA(strMsg)), strMsg.GetLength(), sockAddr);
  110. }
  111. else
  112. {
  113. //AppendText( _T("Please change the port number to send message to a client.\r\n") );
  114. }
  115. }
  116. }
  117. else
  118. {
  119. AfxMessageBox(_T("Socket is not connected"));
  120. }
  121. }
  122. void IServerImpl::SendAll(CSocketHandle &sockHandle, unsigned char *pMsg, int nLength)
  123. {
  124. if ( m_SocketServer.IsOpen() )
  125. {
  126. USES_CONVERSION;
  127. if (m_nSockType == SOCK_TCP)
  128. {
  129. // unsafe access to Socket list!
  130. const LPBYTE lpbData = (const LPBYTE)(pMsg);
  131. sockHandle.Write(lpbData, nLength, NULL);
  132. }
  133. else
  134. {
  135. SockAddrIn servAddr, sockAddr;
  136. m_SocketServer->GetSockName(servAddr);
  137. GetDestination(sockAddr);
  138. if ( servAddr != sockAddr )
  139. {
  140. m_SocketServer.Write((const LPBYTE)*pMsg, nLength, sockAddr);
  141. }
  142. else
  143. {
  144. }
  145. }
  146. }
  147. else
  148. {
  149. }
  150. }
  151. void IServerImpl::ToprocessRecivebuf(IN PerSocketContext &sockHandle, IN const BYTE* pReceivebuf, IN DWORD dwReceiveSize)
  152. {
  153. }
  154. int IServerImpl::OnIntegrityPacket(IN PerSocketContext &sockHandle, IN void *pIntegrityPacket)
  155. {
  156. return 0;
  157. }
  158. void IServerImpl::GetAddress(const SockAddrIn& addrIn, CString& rString) const
  159. {
  160. TCHAR szIPAddr[MAX_PATH] = { 0 };
  161. CSocketHandle::FormatIP(szIPAddr, MAX_PATH, addrIn);
  162. rString.Format(_T("%s : %d"), szIPAddr, static_cast<int>(static_cast<UINT>(ntohs(addrIn.GetPort()))) );
  163. }
  164. void IServerImpl::AppendText(LPCTSTR lpszFormat, ...)
  165. {
  166. // if ( !::IsWindow(m_ctlMsgList.GetSafeHwnd()) ) return;
  167. // TCHAR szBuffer[512];
  168. // HWND hWnd = m_ctlMsgList.GetSafeHwnd();
  169. // DWORD dwResult = 0;
  170. // if (SendMessageTimeout(hWnd, WM_GETTEXTLENGTH, 0, 0, SMTO_NORMAL, 500L, &dwResult) != 0)
  171. // {
  172. // int nLen = (int) dwResult;
  173. // if (SendMessageTimeout(hWnd, EM_SETSEL, nLen, nLen, SMTO_NORMAL, 500L, &dwResult) != 0)
  174. // {
  175. // size_t cb = 0;
  176. // va_list args;
  177. // va_start(args, lpszFormat);
  178. // ::StringCchVPrintfEx(szBuffer, 512, NULL, &cb, 0, lpszFormat, args);
  179. // va_end(args);
  180. // SendMessageTimeout(hWnd, EM_REPLACESEL, FALSE, reinterpret_cast<LPARAM>(szBuffer), SMTO_NORMAL, 500L, &dwResult);
  181. // }
  182. // }
  183. }
  184. bool IServerImpl::GetDestination(SockAddrIn& addrIn) const
  185. {
  186. CString strPort;
  187. //GetDlgItemText(IDC_SVR_PORT, strPort);
  188. int nFamily = (m_nMode == AF_IPV4) ? AF_INET : AF_INET6;
  189. return addrIn.CreateFrom(NULL, strPort, nFamily);
  190. }
  191. bool IServerImpl::SetupMCAST()
  192. {
  193. const TCHAR szIPv4MCAST[] = TEXT("239.121.1.2");
  194. const TCHAR szIPv6MCAST[] = TEXT("FF02:0:0:0:0:0:0:1"); // All Nodes local address
  195. bool result = false;
  196. if ( m_nSockType == SOCK_UDP )
  197. {
  198. if ( m_nMode == AF_IPV4 ) {
  199. result = m_SocketServer->AddMembership(szIPv4MCAST, NULL);
  200. } else {
  201. result = m_SocketServer->AddMembership(szIPv6MCAST, NULL);
  202. HRESULT hr = HRESULT_FROM_WIN32(GetLastError());
  203. hr = hr;
  204. }
  205. }
  206. return result;
  207. }
  208. ///////////////////////////////////////////////////////////////////////////////
  209. void IServerImpl::OnThreadBegin(CSocketHandle* pSH)
  210. {
  211. ASSERT( pSH == m_SocketServer );
  212. (pSH);
  213. CString strAddr;
  214. SockAddrIn sockAddr;
  215. m_SocketServer->GetSockName(sockAddr);
  216. GetAddress( sockAddr, strAddr );
  217. //AppendText( _T("Server Running on: %s\r\n"), strAddr);
  218. }
  219. void IServerImpl::OnThreadExit(CSocketHandle* pSH)
  220. {
  221. ASSERT( pSH == m_SocketServer );
  222. (pSH);
  223. //AppendText( _T("Server Down!\r\n"));
  224. }
  225. void IServerImpl::OnConnectionFailure(CSocketHandle* pSH, SOCKET newSocket)
  226. {
  227. ASSERT( pSH == m_SocketServer );
  228. (pSH);
  229. CString strAddr;
  230. CSocketHandle sockHandle;
  231. SockAddrIn sockAddr;
  232. if (newSocket != INVALID_SOCKET)
  233. {
  234. sockHandle.Attach( newSocket );
  235. sockHandle.GetPeerName( sockAddr );
  236. GetAddress( sockAddr, strAddr );
  237. sockHandle.Close();
  238. //AppendText( _T("Connection abandoned: %s\r\n"), strAddr );
  239. //LOG4C_NO_FILENUM((LOG_NOTICE,"Connection abandoned:%s",strAddr));
  240. //OutputDebugString(_T("\n客户端连接中断:"));
  241. //OutputDebugString(strAddr);
  242. //OutputDebugString(_T("\n\n"));
  243. }
  244. else
  245. {
  246. //OutputDebugString(_T("\n客户端连接中断,不是一个有效的套接字:"));
  247. //OutputDebugString(strAddr);
  248. //OutputDebugString(_T("\n\n"));
  249. //AppendText( _T("Connection abandoned. Not a valid socket.\r\n"), strAddr );
  250. //LOG4C_NO_FILENUM((LOG_NOTICE,"Connection abandoned. Not a valid socket:%s",strAddr));
  251. }
  252. }
  253. void IServerImpl::OnAddConnection(CSocketHandle* pSH, SOCKET newSocket)
  254. {
  255. ASSERT( pSH == m_SocketServer );
  256. (pSH);
  257. CString strAddr;
  258. CSocketHandle sockHandle;
  259. SockAddrIn sockAddr;
  260. sockHandle.Attach( newSocket );
  261. sockHandle.GetPeerName( sockAddr );
  262. GetAddress( sockAddr, strAddr );
  263. sockHandle.Detach();
  264. //OutputDebugString(_T("\n新的连接接入:"));
  265. //OutputDebugString(strAddr);
  266. //OutputDebugString(_T("\n"));
  267. //*、、*/LOG4C_NO_FILENUM((LOG_NOTICE,"新的连接接入:%s",strAddr));
  268. //AppendText( _T("Connection established: %s\r\n"), strAddr );
  269. }
  270. void IServerImpl::OnDataReceived(CSocketHandle* pSH, const SOCKET sClient, const BYTE* pbData, DWORD dwCount, const SockAddrIn& addr, BYTE **pendingbuf, unsigned int& npendingSize, unsigned int& ncursize)
  271. {
  272. ASSERT( pSH == m_SocketServer );
  273. (pSH);
  274. CString strAddr, strText;
  275. //USES_CONVERSION;
  276. //LPTSTR pszText = strText.GetBuffer(dwCount+1);
  277. //::StringCchCopyN(pszText, dwCount+1, A2CT(reinterpret_cast<LPCSTR>(pbData)), dwCount);
  278. //strText.ReleaseBuffer();
  279. GetAddress( addr, strAddr );
  280. //AppendText( _T("%s>(%s)\r\n"), strAddr, strText);
  281. const SocketContextList& sl = m_SocketServer.GetClientSocketList();
  282. CClientProcess::GetInstance()->ClientProcess(sClient, pbData, dwCount, strAddr, pendingbuf, npendingSize, ncursize);
  283. }
  284. void IServerImpl::OnConnectionDropped(CSocketHandle* pSH)
  285. {
  286. ASSERT( pSH == m_SocketServer );
  287. (pSH);
  288. CString strAddr;
  289. //AppendText( _T("Connection lost with client.\r\n") );
  290. //LOG4C_NO_FILENUM((LOG_NOTICE,"Connection lost with client"));
  291. }
  292. void IServerImpl::OnConnectionError(CSocketHandle* pSH, DWORD dwError)
  293. {
  294. ASSERT( pSH == m_SocketServer );
  295. (pSH);
  296. _com_error err(dwError);
  297. //AppendText( _T("Communication Error:\r\n%s\r\n"), err.ErrorMessage() );
  298. //LOG4C((LOG_NOTICE,"Communication Error:%s",err.ErrorMessage()));
  299. }
  300. #if defined(SOCKHANDLE_USE_OVERLAPPED)
  301. void IServerImpl::OnRemoveConnection(CSocketHandle* pSH, SOCKET dropSocket)
  302. {
  303. return;
  304. ASSERT( pSH == m_SocketServer );
  305. (pSH);
  306. CString strAddr;
  307. CSocketHandle sockHandle;
  308. SockAddrIn sockAddr;
  309. sockHandle.Attach( dropSocket );
  310. sockHandle.GetPeerName( sockAddr );
  311. GetAddress( sockAddr, strAddr );
  312. sockHandle.Detach();
  313. //LOG4C_NO_FILENUM((LOG_NOTICE,"Connection abandoned. Not a valid socket:%s",strAddr));
  314. }
  315. #endif
  316. DWORD IServerImpl::GetClientConnectCount()
  317. {
  318. //DWORD dwClientSize = 0;
  319. //m_SocketServer->GetConnectionCount();
  320. return m_SocketServer.GetConnectionCount();
  321. }
  322. void IServerImpl::StartClearInvalidateSocketThread()
  323. {
  324. m_hRunObject = CreateEvent( NULL, TRUE, FALSE, _T("ClearInvalidateSocketThread") );
  325. if ( m_hRunObject == NULL )
  326. {
  327. // LOG4C((LOG_NOTICE,"创建事件失败"));
  328. }
  329. m_hClearInvalidateSocketThread = CreateThread(NULL,0,ClearInvalidateSocketThread,this,0,NULL);
  330. if ( m_hClearInvalidateSocketThread == NULL )
  331. {
  332. // LOG4C((LOG_NOTICE,"创建线程失败"));
  333. }
  334. }
  335. DWORD WINAPI IServerImpl::ClearInvalidateSocketThread(void *pInstance)
  336. {
  337. //LOG4C((LOG_NOTICE,"服务端心跳检测线程"));
  338. IServerImpl *pServerImpl = (IServerImpl*)pInstance;
  339. #ifdef SOCKHANDLE_USE_OVERLAPPED
  340. /*const*/ SocketContextList& sl = pServerImpl->m_SocketServer.GetClientSocketList();
  341. SocketContextList::iterator citer = sl.begin();
  342. #else
  343. /*const*/ SocketList& sl = pServerImpl->m_SocketServer.GetClientSocketList();
  344. SocketList::const_iterator citer = sl.begin();
  345. #endif
  346. //SockAddrIn sockAddr;
  347. //size_t nSize = sl.size();
  348. DWORD dwError;
  349. //CSocketHandle tSocketHandle;
  350. do
  351. {
  352. //nSize = sl.size();
  353. if ( !pServerImpl->m_bStopbeat )
  354. {
  355. //AutoThreadSection aSenction(pServerImpl->m_SocketServer.ReturnSection());
  356. //if( (nSize != 0) && (citer != sl.end()))
  357. if ( citer != sl.end())
  358. {
  359. //SocketIOBuffer *buf = citer;
  360. DWORD dwTick = GetTickCount();
  361. //if ( ( dwTick - citer->dwTime) > 5000 )
  362. //{
  363. SOCKET sokt = static_cast<SOCKET>(*citer++);
  364. WORD wMessageId = MSG_LOGIN_RESP;
  365. LOGIN_RESULT_STRU tLoginResult = {0};
  366. tLoginResult.tCommonMsg.dwConnectionID = 0;
  367. tLoginResult.tCommonMsg.wMessageId = wMessageId;
  368. tLoginResult.byResult = LOGIN_RESULT_SUC;
  369. tLoginResult.dwUserID = 0;
  370. tLoginResult.byStatus = USER_STATUS_ONLINE ;
  371. DWORD dwDataLen = sizeof(LOGIN_RESULT_STRU);
  372. TMessageHeader tHeader = {0};
  373. tHeader.wMessageId = wMessageId;
  374. tHeader.dwDataLen = dwDataLen;
  375. CSocketHandle hClient;
  376. hClient.Attach(sokt);
  377. INT nRet = CClientProcess::net_Send(&hClient, &tHeader, (void *)&tLoginResult, dwDataLen);
  378. hClient.Detach();
  379. if ( nRet <= 0 )
  380. {
  381. pServerImpl->m_SocketServer.RemoveConnection(sokt);
  382. pServerImpl->m_SocketServer.CloseConnection(sokt);
  383. }
  384. //}
  385. //else
  386. //{
  387. // citer++;
  388. //}
  389. //tSocketHandle.Attach( (*citer) );
  390. #if 0
  391. //tSocketHandle.Write(LPBYTE("0"), 1, NULL, 30000); // 心跳包超时值:30秒到1分钟为好!
  392. dwError = WSAGetLastError();
  393. switch( dwError )
  394. {
  395. case WSAENOTSOCK:
  396. case WSAENETDOWN:
  397. case WSAENETUNREACH:
  398. case WSAENETRESET:
  399. case WSAECONNABORTED:
  400. case WSAECONNRESET:
  401. case WSAESHUTDOWN:
  402. case WSAEHOSTDOWN:
  403. case WSAEHOSTUNREACH:
  404. //citer = sl.erase(citer);
  405. LOG4C_NO_FILENUM((LOG_NOTICE,"删除过期客户端连接"));
  406. //pServerImpl->m_SocketServer.CloseConnection(*citer);
  407. //pServerImpl->m_SocketServer.RemoveConnection(*citer);
  408. citer = sl.begin();
  409. default:
  410. //TRACE("--------------%d\r\n",dwError);
  411. if( citer != sl.end() )
  412. citer++;
  413. break;
  414. }
  415. #endif
  416. //tSocketHandle.Detach();
  417. }
  418. else if ( citer == sl.end() )
  419. {
  420. citer = sl.begin();
  421. }
  422. }
  423. } while (WaitForSingleObject(pServerImpl->m_hRunObject,5000L) == WAIT_TIMEOUT);
  424. return 0;
  425. }
  426. };