view modules/net/examples/non-blocking-connect.cpp @ 512:0002b8da93dc

Net: rework a lot, going to stabilization soon
author David Demelier <markand@malikania.fr>
date Mon, 04 Apr 2016 17:34:01 +0200
parents
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 milliseconds before giving up (default: 3000)
 *   - 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 3000
#endif

#include "elapsed-timer.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;
	net::Condition cond;
	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), &cond);

		while (cond != net::Condition::None && timer.elapsed() < WITH_TIMEOUT) {
			listener.remove(socket.handle());

			// 2. Now complete by waiting for the appropriate condition.
			listener.set(socket.handle(), cond);
			listener.wait(std::chrono::milliseconds(WITH_TIMEOUT - timer.elapsed()));
			socket.connect(&cond);
		}
	} catch (const net::Error &error) {
		std::cerr << "error: " << error.what() << std::endl;
		std::exit(1);
	}

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

	return 0;
}