diff 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 diff
--- a/C++/examples/Socket/non-blocking-connect.cpp	Thu Nov 05 16:42:23 2015 +0100
+++ b/C++/examples/Socket/non-blocking-connect.cpp	Thu Nov 05 22:28:40 2015 +0100
@@ -28,39 +28,33 @@
 int main()
 {
 #if defined(WITH_SSL)
-	net::SocketTls<net::Ipv4> socket;
+	net::SocketTls<net::address::Ip> socket;
 #else
-	net::SocketTcp<net::Ipv4> socket;
+	net::SocketTcp<net::address::Ip> socket;
 #endif
 
 	net::Listener<> listener;
 	ElapsedTimer timer;
 
-	socket.setBlockMode(false);
+	// 1. Set to non-blocking.
+	socket.set(net::option::SockBlockMode{false});
 
 	try {
 		std::cout << "Trying to connect to " << WITH_HOST << ":" << WITH_PORT << std::endl;
-		socket.connect(net::Ipv4{WITH_HOST, WITH_PORT});
+
+		// 2. Initial connection process.
+		socket.connect(net::address::Ip{WITH_HOST, WITH_PORT});
 
 		while (socket.state() != net::State::Connected) {
 			listener.remove(socket.handle());
 
-			if (socket.state() == net::State::ConnectingRead) {
-				listener.set(socket.handle(), net::FlagRead);
-			} else if (socket.state() == net::State::ConnectingWrite) {
-				listener.set(socket.handle(), net::FlagWrite);
-			}
-
+			// 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) {
-		if (error.code() == net::Error::Timeout) {
-			std::cerr << "timeout while connecting" << std::endl;
-		} else {
-			std::cerr << "error: " << error.what() << std::endl;
-		}
-
+		std::cerr << "error: " << error.what() << std::endl;
 		std::exit(1);
 	}