title: C++ winsock problem reconnecting socket after it has been closed
body: <p>I am building an application that uses Windows sockets for communication. The <code>Client</code> class handles the connection and spawns a thread that should periodically check if the connection is alive and if it's not, it should try to reconnect.</p>
  <pre><code>bool Client::Connect() {
      fSocket = WSASocket(AF_INET, SOCK_STREAM, IPPROTO_TCP, nullptr, NULL, NULL);
      if (WSAConnect(fSocket, (SOCKADDR*) &amp;fAddress, sizeof(fAddress), nullptr, nullptr, nullptr, nullptr) != 0) {
          return false;
      }
      return true;
  }
  
  void Client::StartConnectionAndKeepAlive() {
      auto threadFunction = [this]() {
          while (true) {
              if (!this-&gt;fConnected) {
                  this-&gt;CloseConnection();
                  this-&gt;Connect();
                  this-&gt;Send(&quot;Hello from thread!\n&quot;);
              }
              this_thread::sleep_for(chrono::seconds(1));
          }
      };
      fThread = new thread(threadFunction);
  }
  
  bool Client::Send(const string&amp; data) {
      auto nBytesSent = send(fSocket, data.c_str(), int(data.size()), NULL);
      cout &lt;&lt; &quot;nBytesSent: &quot; &lt;&lt; nBytesSent &lt;&lt; &quot; for data: &quot; &lt;&lt; data &lt;&lt; endl;
      if (nBytesSent == SOCKET_ERROR) {
          fConnected = false;
          return false;
      }
      fConnected = true;
      return true;
  }
  </code></pre>
  <p>After instantiating <code>Client</code>, <code>Client::StartConnectionAndKeepAlive()</code> is called. If the connection is not possible, the value of <code>send</code> will be equal to <code>SOCKET_ERROR</code> as expected.</p>
  <p>However my problem is when the server closes the connection (I am currently using <code>netcat</code> and close the connection just by <code>ctrl+C</code>). After closing the connection the return value of <code>send</code> is the same as when the connection is alive. This causes the flag <code>fConnected</code> to stay true and therefor the connection won't be restablished even if I launch <code>netcat</code> again.</p>
  <p>This is the first time I am working with sockets and windows so I am surely mising something but I couldn't find a solution online. All similar question responses state that the return value of <code>send</code> should be <code>SOCKET_ERROR</code> if there is no connection (if I understood them correctly) but I found it's not the case.</p>
  <p>I am aware that I should probably use <code>std::mutex</code> in my class since I am using it from multiple threads but found that adding it doesn't make my problem disappear, I removed them to keep the code simpler.</p>
  <p>Any feedback to my implementation is also welcome! Thanks!</p>