Goby v2
tcp_client.cpp
1 // Copyright 2009-2018 Toby Schneider (http://gobysoft.org/index.wt/people/toby)
2 // GobySoft, LLC (2013-)
3 // Massachusetts Institute of Technology (2007-2014)
4 // Community contributors (see AUTHORS file)
5 //
6 //
7 // This file is part of the Goby Underwater Autonomy Project Libraries
8 // ("The Goby Libraries").
9 //
10 // The Goby Libraries are free software: you can redistribute them and/or modify
11 // them under the terms of the GNU Lesser General Public License as published by
12 // the Free Software Foundation, either version 2.1 of the License, or
13 // (at your option) any later version.
14 //
15 // The Goby Libraries are distributed in the hope that they will be useful,
16 // but WITHOUT ANY WARRANTY; without even the implied warranty of
17 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 // GNU Lesser General Public License for more details.
19 //
20 // You should have received a copy of the GNU Lesser General Public License
21 // along with Goby. If not, see <http://www.gnu.org/licenses/>.
22 
23 #include "goby/common/logger.h"
24 #include "goby/util/as.h"
25 
26 #include "tcp_client.h"
27 
28 goby::util::TCPClient::TCPClient(const std::string& server, unsigned port,
29  const std::string& delimiter /*= "\r\n"*/,
30  int retry_interval /*= 10*/)
31  : LineBasedClient<boost::asio::ip::tcp::socket>(delimiter, retry_interval),
32  socket_(io_service_), server_(server), port_(as<std::string>(port))
33 {
34 }
35 
36 bool goby::util::TCPClient::start_specific()
37 {
38  using namespace goby::common::logger;
39  using goby::glog;
40 
41  boost::asio::ip::tcp::resolver resolver(io_service_);
42  boost::asio::ip::tcp::resolver::query query(
43  server_, port_, boost::asio::ip::resolver_query_base::numeric_service);
44 
45  boost::system::error_code resolver_error = boost::asio::error::host_not_found;
46  boost::asio::ip::tcp::resolver::iterator endpoint_iterator =
47  resolver.resolve(query, resolver_error);
48  if (resolver_error)
49  {
50  glog.is(WARN) && glog << "Error resolving address: " << server_ << ":" << port_ << ": "
51  << resolver_error.message() << std::endl;
52  return false;
53  }
54 
55  boost::asio::ip::tcp::resolver::iterator end;
56 
57  boost::system::error_code error = boost::asio::error::host_not_found;
58  while (error && endpoint_iterator != end)
59  {
60  socket_.close();
61  socket_.connect(*endpoint_iterator++, error);
62  }
63 
64  if (error)
65  glog.is(WARN) && glog << "Error connecting to address: " << server_ << ":" << port_ << ": "
66  << error.message() << std::endl;
67 
68  return error ? false : true;
69 }
Definition: time.h:241
STL namespace.
common::FlexOstream glog
Access the Goby logger through this object.
TCPClient(const std::string &server, unsigned port, const std::string &delimiter="\r\n", int retry_interval=10)
create a TCPClient
Definition: tcp_client.cpp:28