Mercurial > code
view C++/examples/Socket/non-blocking-accept.cpp @ 473:5a9671dabb15
Socket:
- Fix epoll which wrongly reset flags,
- Fix wrongly use of SOCKET_DEFAULT_BACKEND,
- Fix error in GCC using constexpr, switch to inline,
- Add more documentation about non-blocking sockets,
- Remove Socket::setBlockMode,
- Start updating all doxygen comments,
- Put back UDP.
author | David Demelier <markand@malikania.fr> |
---|---|
date | Thu, 05 Nov 2015 22:28:40 +0100 |
parents | 41d1a36cc461 |
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 seconds before giving up (default: 60) * - WITH_SSL (bool), true to test with SSL (default: false) */ #include <iostream> #include "ElapsedTimer.h" #include "Sockets.h" #if !defined(WITH_PORT) # define WITH_PORT 16000 #endif #if !defined(WITH_TIMEOUT) # define WITH_TIMEOUT 60 #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; 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(); } catch (const net::Error &error) { std::cerr << "error: " << error.what() << std::endl; std::exit(1); } while (client.state() != net::State::Accepted && timer.elapsed() < (WITH_TIMEOUT * 1000)) { try { if (client.state() == net::State::Closed) { // 2. Wait for a pre-accept process. listener.set(master.handle(), net::Condition::Readable); listener.wait(std::chrono::seconds(WITH_TIMEOUT)); client = master.accept(nullptr); client.set(net::option::SockBlockMode{false}); listener.remove(master.handle()); } else { // 3. Wait for the accept process to complete. listener.remove(client.handle()); listener.set(client.handle(), client.condition()); listener.wait(std::chrono::seconds(WITH_TIMEOUT)); client.accept(); } } catch (const net::Error &error) { std::cerr << error.function() << ": " << error.what() << std::endl; std::exit(1); } } std::cout << "Client successfully accepted!" << std::endl; return 0; }