title: Reconnect asio connection when the server is alive
body: <p>I want to keep an asio connection responsive, that I mean to check the server every second till it become alive and then send and receive. Here is my code</p>
  
  <p>---irunnable.h---</p>
  
  <pre><code>#ifndef IRUNNABLE_H
  #define IRUNNABLE_H
  
  #include &lt;condition_variable&gt;
  #include &lt;atomic&gt;
  #include &lt;thread&gt;
  
  class IRunnable
  {
  public:
      IRunnable(): mThread(nullptr) {
          mRunning.store(false);
      }
  
      virtual ~IRunnable() {
          if (mRunning.load())
              Stop();
          delete mThread;
      }
  
  
      virtual void Start() {
          mRunning.store(true);
          mThread = new std::thread(&amp;IRunnable::Run, this);
      }
  
      virtual void Stop() {
          mRunning.store(false);
          if (mThread &amp;&amp; mThread-&gt;joinable())
              mThread-&gt;join();
      }
  
      virtual bool IsRunning() {return mRunning.load();}
  
  protected:
      virtual void Run() = 0;
  
      std::atomic&lt;bool&gt; mRunning;
  
  private:
      std::thread *mThread;
  };
  
  #endif // IRUNNABLE_H
  </code></pre>
  
  <p>---mytcpconnection.h---</p>
  
  <pre><code>#ifndef MYTCPCONNECTION_H
  #define MYTCPCONNECTION_H
  
  #include &lt;asio/io_service.hpp&gt;
  #include &lt;asio/ip/tcp.hpp&gt;
  #include "irunnable.h"
  
  
  class MyTCPConnection : public IRunnable
  {
  public:
      MyTCPConnection(const std::string &amp;ip, const std::string &amp;port);
  
      ~MyTCPConnection();
  
      void Stop();
  
      void Write(const std::string &amp;msg);
  
      void Connect();
  protected:
      void Run();
  
  private:
      void readHeader();
  
  private:
      std::string mIP;
      std::string mPort;
      asio::io_service mIOService;
      asio::ip::tcp::socket mSocket;
  };
  
  #endif // MYTCPCONNECTION_H
  </code></pre>
  
  <p>---mytcpconnection.cpp</p>
  
  <pre><code>#include "mytcpconnection.h"
  #include &lt;iostream&gt;
  #include &lt;asio/connect.hpp&gt;
  #include &lt;asio/write.hpp&gt;
  #include &lt;asio/read.hpp&gt;
  
  MyTCPConnection::MyTCPConnection(const std::string &amp;ip, const std::string &amp;port):
      mIP(ip),
      mPort(port),
      mSocket(mIOService)
  {
      Connect();
  }
  
  MyTCPConnection::~MyTCPConnection()
  {
      Stop();
  }
  
  void MyTCPConnection::Stop()
  {
      mIOService.stop();
      mSocket.close();
      IRunnable::Stop();
  }
  
  void MyTCPConnection::Write(const std::string &amp;msg)
  {
      asio::async_write(mSocket,
                      asio::buffer(msg.c_str(),
                                  msg.length()),
                      [this, msg](std::error_code ec, std::size_t /*length*/)
      {
          if (!ec)
          {
              std::cout &lt;&lt;  msg &lt;&lt; std::endl;
          }
          else
          {
              mSocket.close();
          }
      });
  }
  
  
  
  void MyTCPConnection::Run()
  {
  
      while (mRunning.load()) {
          sleep(1);
  //        Connect();
          std::cout &lt;&lt; "before run\n";
          mIOService.run();
          std::cout &lt;&lt; "after run\n";
      }
  
  }
  
  void MyTCPConnection::Connect()
  {
      asio::ip::tcp::resolver resolver(mIOService);
      asio::async_connect(mSocket, resolver.resolve({mIP, mPort}),
                          [this](std::error_code ec, asio::ip::tcp::resolver::iterator)
      {
          if (!ec)
          {
              std::cout &lt;&lt; "readHeader called\n";
              readHeader();
          }
          else {
              std::cout &lt;&lt; "can not connect\n";
              mSocket.close();
              mIOService.reset();
              std::cout &lt;&lt; "after stopping io_service\n";
          }
      });
  }
  
  void MyTCPConnection::readHeader()
  {
      const int header_length = 16;
      std::shared_ptr&lt;char&gt; msg(new char[header_length]{0},
          [](char *c) {
              delete[] c;
      });
      asio::async_read(mSocket,
                      asio::buffer(msg.get(), header_length),
                      [this, msg](std::error_code ec, std::size_t s/*length*/)
      {
          if (!ec)
          {
              std::cout &lt;&lt; "Message read " &lt;&lt; s &lt;&lt; std::endl;
              readHeader();
          }
          else
          {
              std::cout &lt;&lt; "closing socket\n";
              mSocket.close();
              mIOService.stop();
          }
      });
  }
  </code></pre>
  
  <p>---main.cpp---</p>
  
  <pre><code>#include &lt;iostream&gt;
  #include "mytcpconnection.h"
  
  using namespace std;
  
  int main()
  {
      MyTCPConnection conn("127.0.0.1", "12345");
      conn.Start();
  
      while (true)
      {
          conn.Write("Hello server");
  
          sleep(1);
      }
  
      return 0;
  }
  </code></pre>
  
  <p>---server.go---</p>
  
  <pre><code>package main
  
  import (
          "time"
          "fmt"
          "net"
  )
  
  func handle_conn(conn net.Conn) {
      b := make([]byte, 1028)
      for {
          n, err:= conn.Read(b)
          if err != nil {
              fmt.Println(err.Error())
              break
          }
          fmt.Println(string(b[:n]))
          _, _ = conn.Write([]byte("hellohellohello1"))
          time.Sleep(time.Second*1)
      }
  }
  
  func main() {
          ln, err := net.Listen("tcp", ":12345")
          if err != nil {
                  fmt.Println(err.Error())
          }
          fmt.Println("server started")
          for {
                  conn, err := ln.Accept()
          fmt.Println("connection from", conn.RemoteAddr())
                  if err != nil {
                          fmt.Println(err.Error())
                          continue
                  }
                  go handle_conn(conn)
          }
  }
  </code></pre>
  
  <p>In this form, the client connects to the server (when the server is running) and keeps reading and writing. If I move the Connect() method in the mytcpconnection constructor to the Run() function (where it is commented now), the connection is not able to connect to the server. </p>
  
  <p>How can I fix this problem?</p>