Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- TriviaServer::~TriviaServer()
- {
- TRACE(__FUNCTION__ " closing accepting socket");
- try
- {
- for (map<int, Room*>::iterator it = _roomsList.begin(); it != _roomsList.end(); it++)
- delete it->second;
- for (map<SOCKET, User*>::iterator it = _connectedUsers.begin(); it != _connectedUsers.end(); it++)
- delete it->second;
- // the only use of the destructor should be for freeing
- // resources that was allocated in the constructor
- ::closesocket(_socket);
- }
- catch (...) {}
- }
- void TriviaServer::serve()
- {
- bindAndListen();
- // create new thread for handling message
- thread tr(&TriviaServer::handleRecievedMessages, this);
- tr.detach();
- while (true)
- {
- // the main thread is only accepting clients
- // and add then to the list of handlers
- TRACE("accepting client...");
- accept();
- }
- }
- // listen to connecting requests from clients
- // accept them, and create thread for each client
- void TriviaServer::bindAndListen()
- {
- struct sockaddr_in sa = { 0 };
- sa.sin_port = htons(PORT);
- sa.sin_family = AF_INET;
- sa.sin_addr.s_addr = IFACE;
- // again stepping out to the global namespace
- if (::bind(_socket, (struct sockaddr*)&sa, sizeof(sa)) == SOCKET_ERROR)
- throw std::exception(__FUNCTION__ " - bind");
- TRACE("binded");
- if (::listen(_socket, SOMAXCONN) == SOCKET_ERROR)
- throw std::exception(__FUNCTION__ " - listen");
- TRACE("listening...");
- }
- void TriviaServer::accept()
- {
- SOCKET client_socket = ::accept(_socket, NULL, NULL);
- if (client_socket == INVALID_SOCKET)
- throw std::exception(__FUNCTION__);
- TRACE("Client accepted !");
- // create new thread for client and detach from it
- std::thread tr(&TriviaServer::clientHandler, this, client_socket);
- tr.detach();
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement