Mercurial > code
view modules/sockets/examples/non-blocking-accept.cpp @ 509:36e81ef34ed5
Sockets: update examples
author | David Demelier <markand@malikania.fr> |
---|---|
date | Tue, 23 Feb 2016 12:56:41 +0100 |
parents | 8b161d143975 |
children |
line wrap: on
line source
/* * non-blocking-accept.cpp -- example of total non-blocking accept * * Options: * - WITH_PORT (int), the port to use (default: 16000) * - WITH_TIMEOUT (int), number of milliseconds before giving up (default: 3000) * - WITH_SSL (bool), true to test with SSL (default: false) */ #include <iostream> #include "elapsed-timer.h" #include "sockets.h" #if !defined(WITH_PORT) # define WITH_PORT 16000 #endif #if !defined(WITH_TIMEOUT) # define WITH_TIMEOUT 3000 #endif int main() { #if defined(WITH_SSL) net::SocketTls<net::address::Ip> master; net::SocketTls<net::address::Ip> client{net::Invalid}; #else net::SocketTcp<net::address::Ip> master; net::SocketTcp<net::address::Ip> client{net::Invalid}; #endif net::Listener<> listener; net::Condition cond; ElapsedTimer timer; // 1. Create the master socket for listening. try { master.set(net::option::SockReuseAddress{true}); master.set(net::option::SockBlockMode{false}); master.bind(net::address::Ip{"*", WITH_PORT}); master.listen(); listener.set(master.handle(), net::Condition::Readable); } catch (const net::Error &error) { std::cerr << "error: " << error.what() << std::endl; std::exit(1); } while (!client.isOpen() && timer.elapsed() < WITH_TIMEOUT) { try { if (!client.isOpen()) { // 2. Wait for a pre-accept process. listener.wait(std::chrono::seconds(WITH_TIMEOUT)); master.accept(client, nullptr, &cond); client.set(net::option::SockBlockMode(false)); listener.remove(master.handle()); std::cout << "Accepting new client" << std::endl; if (cond != net::Condition::None) { std::cout << "Client accept state not complete" << std::endl; listener.set(client.handle(), cond); } } else { // 3. Wait for the accept process to complete. std::cout << "Continuing accept for the client" << std::endl; listener.wait(std::chrono::seconds(WITH_TIMEOUT - timer.elapsed())); client.accept(&cond); listener.remove(client.handle()); if (cond != net::Condition::None) { std::cout << "Client accept state not complete" << std::endl; listener.set(client.handle(), cond); } } } catch (const net::Error &error) { std::cerr << error.function() << ": " << error.what() << std::endl; std::exit(1); } } if (client.isOpen()) std::cout << "Client successfully accepted!" << std::endl; return 0; }