title: How to connect() with a non-blocking socket?
body: <p>In Python, I would like to use <code>socket.connect()</code> on a socket that I have set to non-blocking. When I try to do this, the method always throws a <code>BlockingIOError</code>. When I ignore the error (as below) the program executes as expected. When I set the socket to non-blocking after it is connected, there are no errors. When I use select.select() to ensure the socket is readable or writable, I still get the error.</p>
  
  <p><strong>testserver.py</strong></p>
  
  <pre><code>import socket
  import select
  
  sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  sock.setblocking(0)
  
  host = socket.gethostname()
  port = 1234
  
  sock.bind((host, port))
  sock.listen(5)
  
  while True:
      select.select([sock], [], [])
      con, addr = sock.accept()
      message = con.recv(1024).decode('UTF-8')
      print(message)
  </code></pre>
  
  <p><strong>testclient.py</strong></p>
  
  <pre><code>import socket
  import select
  
  sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  sock.setblocking(0)
  
  host = socket.gethostname()
  port = 1234
  
  try:
      sock.connect((host, port))
  except BlockingIOError as e:
      print("BlockingIOError")
  
  msg = "--&gt; From the client\n"
  
  select.select([], [sock], [])
  if sock.send(bytes(msg, 'UTF-8')) == len(msg):
      print("sent ", repr(msg), " successfully.")
  
  sock.close()
  </code></pre>
  
  <p><strong>terminal 1</strong></p>
  
  <pre><code>$ python testserver.py
  --&gt; From the client
  </code></pre>
  
  <p><strong>terminal 2</strong></p>
  
  <pre><code>$ python testclient.py
  BlockingIOError
  sent  '--&gt; From the client\n'  successfully.
  </code></pre>
  
  <p>This code works correctly except for the BlockingIOError on the first connect(). The documentation for the error reads like this: <code>Raised when an operation would block on an object (e.g. socket) set for non-blocking operation.</code> </p>
  
  <p><strong>How do I properly connect() with a socket set to non-blocking? Can I make connect() non-blocking? Or is it appropriate to just ignore the error?</strong></p>