Advertisement
Guest User

Srsly? -.-

a guest
Jun 22nd, 2017
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.72 KB | None | 0 0
  1. TriviaServer::~TriviaServer()
  2. {
  3.     TRACE(__FUNCTION__ " closing accepting socket");
  4.     try
  5.     {
  6.         for (map<int, Room*>::iterator it = _roomsList.begin(); it != _roomsList.end(); it++)
  7.             delete it->second;
  8.  
  9.         for (map<SOCKET, User*>::iterator it = _connectedUsers.begin(); it != _connectedUsers.end(); it++)
  10.             delete it->second;
  11.         // the only use of the destructor should be for freeing
  12.         // resources that was allocated in the constructor
  13.         ::closesocket(_socket);
  14.     }
  15.     catch (...) {}
  16. }
  17.  
  18. void TriviaServer::serve()
  19. {
  20.     bindAndListen();
  21.  
  22.     // create new thread for handling message
  23.     thread tr(&TriviaServer::handleRecievedMessages, this);
  24.     tr.detach();
  25.  
  26.     while (true)
  27.     {
  28.         // the main thread is only accepting clients
  29.         // and add then to the list of handlers
  30.         TRACE("accepting client...");
  31.         accept();
  32.     }
  33. }
  34.  
  35.  
  36. // listen to connecting requests from clients
  37. // accept them, and create thread for each client
  38. void TriviaServer::bindAndListen()
  39. {
  40.     struct sockaddr_in sa = { 0 };
  41.     sa.sin_port = htons(PORT);
  42.     sa.sin_family = AF_INET;
  43.     sa.sin_addr.s_addr = IFACE;
  44.     // again stepping out to the global namespace
  45.     if (::bind(_socket, (struct sockaddr*)&sa, sizeof(sa)) == SOCKET_ERROR)
  46.         throw std::exception(__FUNCTION__ " - bind");
  47.     TRACE("binded");
  48.  
  49.     if (::listen(_socket, SOMAXCONN) == SOCKET_ERROR)
  50.         throw std::exception(__FUNCTION__ " - listen");
  51.     TRACE("listening...");
  52. }
  53.  
  54. void TriviaServer::accept()
  55. {
  56.     SOCKET client_socket = ::accept(_socket, NULL, NULL);
  57.     if (client_socket == INVALID_SOCKET)
  58.         throw std::exception(__FUNCTION__);
  59.  
  60.     TRACE("Client accepted !");
  61.     // create new thread for client and detach from it
  62.     std::thread tr(&TriviaServer::clientHandler, this, client_socket);
  63.     tr.detach();
  64.  
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement