Listing 3: NetworkService, a generic network server.
struct NetworkService { ... // sub-classes overwrite this method and close socket virtual void ServiceHandler(int socket) = 0; virtual bool stop() { return false; } void operator()() { int server = createServerSocket( sourcePort, lengthWaitList+1); if(server < 0) { std::cout << "Can't bind to port " << sourcePort << std::endl; return; } RunPool<SocketHandler> pool(numThreads); ThreadPool<SocketHandler> thpool(pool, numThreads > 256 ? 256 : numThreads); // start the pool... boost::thread thrd(thpool); std::cout << "Ready... service at port " << sourcePort << std::endl; while (!stop()) { struct sockaddr_in pin; int source = acceptClientSocket(server, pin); if(source < 0) continue; // put handler on the heap so we can delete this later... SocketHandler * linkage = new SocketHandler(*this, source); thpool.execute(linkage); } thrd.join(); CloseConnection(server); std::cout << "Shutting down network service " << serviceId << " at port " << sourcePort << std::endl; } ... }; void SocketHandler::operator()() { try { ns_.ServiceHandler(client_); } catch (...) {} delete this; }