Mercurial > code
view C++/examples/Socket/non-blocking-connect.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-connect.cpp -- example of non blocking connect * * Options: * - WITH_HOST (string literal), the host to try (default: "malikania.fr") * - WITH_PORT (int), the port to use (default: 80) * - WITH_TIMEOUT (int), number of seconds before giving up (default: 30) * - WITH_SSL (bool), true to test with SSL (default: false) */ #include <iostream> #if !defined(WITH_HOST) # define WITH_HOST "malikania.fr" #endif #if !defined(WITH_PORT) # define WITH_PORT 80 #endif #if !defined(WITH_TIMEOUT) # define WITH_TIMEOUT 30 #endif #include "ElapsedTimer.h" #include "Sockets.h" int main() { #if defined(WITH_SSL) net::SocketTls<net::address::Ip> socket; #else net::SocketTcp<net::address::Ip> socket; #endif net::Listener<> listener; ElapsedTimer timer; // 1. Set to non-blocking. socket.set(net::option::SockBlockMode{false}); try { std::cout << "Trying to connect to " << WITH_HOST << ":" << WITH_PORT << std::endl; // 2. Initial connection process. socket.connect(net::address::Ip{WITH_HOST, WITH_PORT}); while (socket.state() != net::State::Connected) { listener.remove(socket.handle()); // 2. Now complete by waiting for the appropriate condition. listener.set(socket.handle(), socket.condition()); listener.wait(std::chrono::seconds(WITH_TIMEOUT)); socket.connect(); } } catch (const net::Error &error) { std::cerr << "error: " << error.what() << std::endl; std::exit(1); } if (socket.state() == net::State::Connected) { std::cout << "Successfully connected!" << std::endl; } return 0; }