1 | #include <iostream>
|
---|
2 | #include <boost\asio.hpp>
|
---|
3 | #include <boost\shared_ptr.hpp>
|
---|
4 | #include <boost\bind.hpp>
|
---|
5 |
|
---|
6 | using boost::asio::ip::tcp;
|
---|
7 |
|
---|
8 | class tcp_client
|
---|
9 | {
|
---|
10 | public:
|
---|
11 | tcp_client(boost::asio::io_service& io_service, tcp::endpoint& endpoint, long long timeout = 3000000)
|
---|
12 | :m_io_service(io_service),
|
---|
13 | m_endpoint(endpoint),
|
---|
14 | m_timer(io_service),
|
---|
15 | m_timeout(timeout)
|
---|
16 | {
|
---|
17 | connect();
|
---|
18 | }
|
---|
19 |
|
---|
20 | void stop()
|
---|
21 | {
|
---|
22 | m_socket->close();
|
---|
23 | }
|
---|
24 |
|
---|
25 | private:
|
---|
26 |
|
---|
27 | void connect()
|
---|
28 | {
|
---|
29 | m_socket.reset(new tcp::socket(m_io_service));
|
---|
30 |
|
---|
31 | std::cout << "TCP Connection in progress" << std::endl;
|
---|
32 | m_socket->async_connect(m_endpoint,
|
---|
33 | boost::bind(&tcp_client::handle_connect, this,
|
---|
34 | m_socket,
|
---|
35 | boost::asio::placeholders::error)
|
---|
36 | );
|
---|
37 |
|
---|
38 | m_timer.expires_from_now(boost::posix_time::microseconds(m_timeout));
|
---|
39 | m_timer.async_wait(boost::bind(&tcp_client::HandleWait, this, boost::asio::placeholders::error));
|
---|
40 | }
|
---|
41 |
|
---|
42 | void handle_connect(boost::shared_ptr<tcp::socket> socket, const boost::system::error_code& error)
|
---|
43 | {
|
---|
44 | if (!error)
|
---|
45 | {
|
---|
46 | std::cout << "TCP Connection : connected !" << std::endl;
|
---|
47 | m_timer.expires_at(boost::posix_time::pos_infin); // Stop the timer !
|
---|
48 | // Read normally
|
---|
49 | }
|
---|
50 | else
|
---|
51 | {
|
---|
52 | std::cout << "TCP Connection failed" << std::endl;
|
---|
53 | }
|
---|
54 | }
|
---|
55 |
|
---|
56 |
|
---|
57 | public:
|
---|
58 | void HandleWait(const boost::system::error_code& error)
|
---|
59 | {
|
---|
60 | if (!error)
|
---|
61 | {
|
---|
62 | std::cout << "Connection not established..." << std::endl;
|
---|
63 | std::cout << "Trying to close socket..." << std::endl;
|
---|
64 | stop();
|
---|
65 | return;
|
---|
66 | }
|
---|
67 | }
|
---|
68 |
|
---|
69 | boost::asio::io_service& m_io_service;
|
---|
70 | boost::shared_ptr<tcp::socket> m_socket;
|
---|
71 | tcp::endpoint m_endpoint;
|
---|
72 | boost::asio::deadline_timer m_timer;
|
---|
73 | long long m_timeout;
|
---|
74 | };
|
---|
75 |
|
---|
76 | int main()
|
---|
77 | {
|
---|
78 | boost::asio::io_service io_service;
|
---|
79 | tcp::endpoint endpoint(boost::asio::ip::address_v4::from_string("192.168.10.74"), 7171); // invalid address
|
---|
80 | tcp_client tcpc(io_service, endpoint);
|
---|
81 |
|
---|
82 | io_service.run();
|
---|
83 |
|
---|
84 | system("pause");
|
---|
85 | }
|
---|