NetService.cpp 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. #define WIN32_LEAN_AND_MEAN
  2. #include <windows.h>
  3. #include <WinSock2.h>
  4. #include <vector>
  5. #include <thread>
  6. #include <mutex>
  7. #include "../Protocol/win/Protocol.pb.h"
  8. #include "NetService.h"
  9. #include "UserSocket.h"
  10. #include "UserManager.h"
  11. #include "../common/Pool.h"
  12. #define PORT 20916
  13. CNetService& CNetService::GetInstance()
  14. {
  15. static CNetService m;
  16. return m;
  17. }
  18. void CNetService::Start()
  19. {
  20. CUserSocket::InitFnDirector();
  21. WSAData data;
  22. WSAStartup(MAKEWORD(2, 2), &data);
  23. m_hSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
  24. sockaddr_in sin;
  25. sin.sin_family = AF_INET;
  26. sin.sin_addr.s_addr = htonl(INADDR_ANY);
  27. sin.sin_port = htons(PORT);
  28. if (::bind(m_hSocket, (sockaddr*)&sin, sizeof(sin)) == SOCKET_ERROR)
  29. {
  30. printf(" Failed bind() \n");
  31. return;
  32. }
  33. listen(m_hSocket, 5);
  34. m_hEvent = WSACreateEvent();
  35. WSAEventSelect(m_hSocket, m_hEvent, FD_ACCEPT | FD_CLOSE);
  36. CreateIOThread();
  37. _bRunning = true;
  38. //_thread = std::thread(std::bind(&CNetService::Run, this));
  39. }
  40. bool CNetService::CreateIOThread()
  41. {
  42. DWORD dwThreads;
  43. SYSTEM_INFO info;
  44. GetSystemInfo(&info);
  45. dwThreads = info.dwNumberOfProcessors << 1;
  46. m_hCompletePort = CreateIoCompletionPort((HANDLE)-1, NULL, NULL, dwThreads);
  47. for (DWORD i = 0; i < dwThreads; i++)
  48. {
  49. _walkarray.push_back(std::thread(&CIOSocket::IOThread, m_hCompletePort));
  50. }
  51. return true;
  52. }
  53. void CNetService::Run()
  54. {
  55. while (_bRunning)
  56. {
  57. int ret = WaitForSingleObject(m_hEvent, WSA_INFINITE);
  58. if (ret == WSA_WAIT_FAILED || ret == WSA_WAIT_TIMEOUT)
  59. {
  60. continue;
  61. }
  62. else
  63. {
  64. WSANETWORKEVENTS events;
  65. WSAEnumNetworkEvents(m_hSocket, m_hEvent, &events);
  66. if (events.lNetworkEvents & FD_ACCEPT)
  67. {
  68. if (events.iErrorCode[FD_ACCEPT_BIT] == 0)
  69. {
  70. sockaddr_in addr;
  71. int len = sizeof(sockaddr_in);
  72. SOCKET s = accept(m_hSocket, (sockaddr*)&addr, &len);
  73. //if (strcmp(inet_ntoa(addr.sin_addr), "222.71.48.226") != 0)
  74. {
  75. printf("a socket connect %s\n", inet_ntoa(addr.sin_addr));
  76. CUserSocket* ptr = Alloc_Pool<CUserSocket>::GetInstance().Alloc(m_hCompletePort, s);
  77. CUserManager::GetInstance().Add(ptr);
  78. }
  79. }
  80. }
  81. }
  82. }
  83. }