view modules/sockets/examples/blocking-accept.cpp @ 497:8b161d143975

Socket: put back examples that were removed by mistake
author David Demelier <markand@malikania.fr>
date Mon, 14 Dec 2015 09:41:28 +0100
parents
children 36e81ef34ed5
line wrap: on
line source

/*
 * blocking-accept.cpp -- example of 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 "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;

	try {
		master.set(net::option::SockReuseAddress{true});
		master.bind(net::address::Ip{"*", WITH_PORT});
		master.listen();

		listener.set(master.handle(), net::Condition::Readable);
		listener.wait(std::chrono::seconds(WITH_TIMEOUT));

		client = master.accept(nullptr);
	} catch (const net::Error &error) {
		std::cerr << "error: " << error.what() << std::endl;
		std::exit(1);
	}

	std::cout << "Client successfully accepted!" << std::endl;

	return 0;	
}