AirInv Logo  1.00.0
C++ Simulated Airline Inventory Management System library
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Pages
AirInvClient_ASIO.cpp
Go to the documentation of this file.
1 // //////////////////////////////////////////////////////////////////////
2 // Import section
3 // //////////////////////////////////////////////////////////////////////
4 // STL
5 #include <cassert>
6 #include <iostream>
7 #include <string>
8 // Boost.ASIO
9 #include <boost/asio.hpp>
10 // Boost.Array
11 #include <boost/array.hpp>
12 
13 // /////////// M A I N ////////////////
14 int main (int argc, char* argv[]) {
15 
16  // Host name
17  std::string lHostname = "localhost";
18 
19  // Service name (as specified within /etc/services)
20  // The "aria" service corresponds to the port 2624
21  const std::string lServiceName = "aria";
22 
23  try {
24 
25  if (argc >= 2) {
26  lHostname = argv[1];
27  }
28 
29  boost::asio::io_service lIOService;
30 
31  boost::asio::ip::tcp::resolver lResolver (lIOService);
32 
33  boost::asio::ip::tcp::resolver::query lQuery (lHostname, lServiceName);
34 
35  boost::asio::ip::tcp::resolver::iterator itEndPoint =
36  lResolver.resolve (lQuery);
37  boost::asio::ip::tcp::resolver::iterator lEnd;
38 
39  boost::asio::ip::tcp::socket lSocket (lIOService);
40  boost::system::error_code lError = boost::asio::error::host_not_found;
41 
42  //
43  while (lError && itEndPoint != lEnd) {
44  const boost::asio::ip::tcp::endpoint lEndPoint = *itEndPoint;
45 
46  // DEBUG
47  std::cout << "Testing end point: " << std::endl;
48 
49  lSocket.close();
50  lSocket.connect (lEndPoint, lError);
51  ++itEndPoint;
52  }
53 
54  //
55  if (lError) {
56  throw boost::system::system_error (lError);
57  }
58  assert (!lError);
59 
60  // DEBUG
61  const boost::asio::ip::tcp::endpoint lValidEndPoint;
62  std::cout << "Valid end point: " << lValidEndPoint << std::endl;
63 
64  // Send a message to the server
65  const std::string lMessage ("Hello AirInv Server!");
66  boost::asio::write (lSocket, boost::asio::buffer (lMessage),
67  boost::asio::transfer_all(), lError);
68 
69  // Read the reply from the server
70  boost::array<char, 256> lBuffer;
71 
72  size_t lLength = lSocket.read_some (boost::asio::buffer(lBuffer), lError);
73 
74  // Some other error than connection closed cleanly by peer
75  if (lError && lError != boost::asio::error::eof) {
76  throw boost::system::system_error (lError);
77  }
78 
79  // DEBUG
80  std::cout << "Reply from the server: ";
81  std::cout.write (lBuffer.data(), lLength);
82  std::cout << std::endl;
83 
84  } catch (std::exception& lException) {
85  std::cerr << lException.what() << std::endl;
86  }
87 
88  return 0;
89 }