view C++/examples/Socket/non-blocking-connect.cpp @ 458:db738947f359

Socket: - connect() now has a continuation function (no arguments), - add non-blocking-connect.cpp as example.
author David Demelier <markand@malikania.fr>
date Tue, 03 Nov 2015 16:38:48 +0100
parents
children 819bccefce8e
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 "Sockets.h"
#include "ElapsedTimer.h"

int main()
{
#if defined(WITH_SSL)
	net::SocketTls<net::Ipv4> socket;
#else
	net::SocketTcp<net::Ipv4> socket;
#endif

	net::Listener<> listener;
	ElapsedTimer timer;

	socket.setBlockMode(false);

	while (socket.state() != net::State::Connected && timer.elapsed() < (WITH_TIMEOUT * 1000)) {
		try {
			/*
			 * If the socket is in state Open then no connection has been attempted, otherwise if it's Connecting,
			 * then we can just resume the connection process.
			 */
			if (socket.state() == net::State::Open) {
				std::cout << "Trying to connect to " << WITH_HOST << ":" << WITH_PORT << std::endl;
				socket.connect(net::Ipv4{WITH_HOST, WITH_PORT});
			} else {
				socket.connect();
			}
		} catch (const net::Error &error) {
			listener.remove(socket.handle());

			if (error.code() == net::Error::WouldBlockRead) {
				listener.set(socket.handle(), net::FlagRead);
			} else if (error.code() == net::Error::WouldBlockWrite) {
				listener.set(socket.handle(), net::FlagWrite);
			} else {
				std::cerr << "error: " << error.what() << std::endl;
				std::exit(1);
			}

			try {
				listener.wait(std::chrono::seconds(WITH_TIMEOUT));
			} catch (...) {
				std::cerr << "timeout while connecting" << std::endl;
				std::exit(1);
			}
		}
	}

	std::cout << "Successfully connected!" << std::endl;

	return 0;
}