title: Python Tcp disconnect detection
body: <p>I have a simpletcp example: </p>
  
  <pre><code>import socket
  import time
  
  
  TCP_IP = '127.0.0.1'
  TCP_PORT = 81
  BUFFER_SIZE = 1024
  
  s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  s.connect((TCP_IP, TCP_PORT))
  
  while True:
      s.send(bytes('hello', 'UTF-8'))
      time.sleep(1)
  
  s.close()
  </code></pre>
  
  <p>How can I detect, if I lost the connection to the server, and how can I safely reconnect then?</p>
  
  <p>Is it necessary to wait for answer to the server?</p>
  
  <p>UPDATE:</p>
  
  <pre><code>import socket
  import time
  
  TCP_IP = '127.0.0.1'
  TCP_PORT = 81
  BUFFER_SIZE = 1024
  
  def reconnect():
      toBreak = False
      while True:
          s.close()
          try:
              s.connect((TCP_IP, TCP_PORT))
              toBreak = True
          except:
              print ("except")        
          if toBreak:
              break
          time.sleep(1)
  
  
  s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  s.connect((TCP_IP, TCP_PORT))
  
  while True:
      try:    
          s.send(bytes('hello', 'UTF-8'))
          print ("sent hello")
      except socket.error as e:
          reconnect()
  
      time.sleep(1)
  
  s.close()
  </code></pre>
  
  <p>If I break the connection, it raises an error (does not really matter what), and goes to the
  reconnect loop. But after I restore the connection, the connect gives back this error:</p>
  
  <p>OSError: [WinError 10038] An operation was attempted on something that is not a socket</p>
  
  <p>If I restart the script, which calls the same s.connect((TCP_IP, TCP_PORT)), it works fine.</p>