view C++/examples/Socket/blocking-accept.cpp @ 461:41d1a36cc461

Socket: - Add more examples, - Implement new accept function.
author David Demelier <markand@malikania.fr>
date Tue, 03 Nov 2015 21:48:14 +0100
parents
children 5a9671dabb15
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::Ipv4> master;
	net::SocketTls<net::Ipv4> client{net::Invalid};
#else
	net::SocketTcp<net::Ipv4> master;
	net::SocketTcp<net::Ipv4> client{net::Invalid};
#endif

	net::Listener<> listener;

	try {
		master.bind(net::Ipv4{"*", WITH_PORT});
		master.listen();

		listener.set(master.handle(), net::FlagRead);
		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;	
}