Mercurial > code
comparison 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 |
comparison
equal
deleted
inserted
replaced
511:5bab839611f2 | 512:0002b8da93dc |
---|---|
1 /* | |
2 * non-blocking-connect.cpp -- example of non blocking connect | |
3 * | |
4 * Options: | |
5 * - WITH_HOST (string literal), the host to try (default: "malikania.fr") | |
6 * - WITH_PORT (int), the port to use (default: 80) | |
7 * - WITH_TIMEOUT (int), number of milliseconds before giving up (default: 3000) | |
8 * - WITH_SSL (bool), true to test with SSL (default: false) | |
9 */ | |
10 | |
11 #include <iostream> | |
12 | |
13 #if !defined(WITH_HOST) | |
14 # define WITH_HOST "malikania.fr" | |
15 #endif | |
16 | |
17 #if !defined(WITH_PORT) | |
18 # define WITH_PORT 80 | |
19 #endif | |
20 | |
21 #if !defined(WITH_TIMEOUT) | |
22 # define WITH_TIMEOUT 3000 | |
23 #endif | |
24 | |
25 #include "elapsed-timer.h" | |
26 #include "sockets.h" | |
27 | |
28 int main() | |
29 { | |
30 #if defined(WITH_SSL) | |
31 net::SocketTls<net::address::Ip> socket; | |
32 #else | |
33 net::SocketTcp<net::address::Ip> socket; | |
34 #endif | |
35 | |
36 net::Listener<> listener; | |
37 net::Condition cond; | |
38 ElapsedTimer timer; | |
39 | |
40 // 1. Set to non-blocking. | |
41 socket.set(net::option::SockBlockMode(false)); | |
42 | |
43 try { | |
44 std::cout << "Trying to connect to " << WITH_HOST << ":" << WITH_PORT << std::endl; | |
45 | |
46 // 2. Initial connection process. | |
47 socket.connect(net::address::Ip(WITH_HOST, WITH_PORT), &cond); | |
48 | |
49 while (cond != net::Condition::None && timer.elapsed() < WITH_TIMEOUT) { | |
50 listener.remove(socket.handle()); | |
51 | |
52 // 2. Now complete by waiting for the appropriate condition. | |
53 listener.set(socket.handle(), cond); | |
54 listener.wait(std::chrono::milliseconds(WITH_TIMEOUT - timer.elapsed())); | |
55 socket.connect(&cond); | |
56 } | |
57 } catch (const net::Error &error) { | |
58 std::cerr << "error: " << error.what() << std::endl; | |
59 std::exit(1); | |
60 } | |
61 | |
62 std::cout << "Successfully connected!" << std::endl; | |
63 | |
64 return 0; | |
65 } |