title: socket server on a thread not releasing the port after the process terminates
body: <p>The following code runs a socket server on a thread. The client socket sends 'client: hello' to the server, and the server socket receives and replies 'server: world'.</p>
  
  <pre><code>import socket
  import threading
  
  def server():
      sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
      sock.bind(('127.0.0.1', 12345))
      sock.listen(1)
      req, addr = sock.accept()
      print req.recv(1024)
      req.sendall('server: world')
  
  def client():
      sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
      sock.connect(('127.0.0.1', 12345))
      sock.sendall('client: hello')
      print sock.recv(1024)
  
  def main():
      t = threading.Thread(target=server)
      t.start()
      client()
  
  if __name__ == '__main__':
      main()
  </code></pre>
  
  <p>It runs ok as expected the first time, but from the second time, if you do not wait for a good few seconds for the server to release the socket, and if you try this on a Linux machine or Mac (Windows do not get it somehow) you will run into this error:</p>
  
  <pre><code>Traceback (most recent call last):
    File "socket_send_receive.py", line 24, in &lt;module&gt;
      main()
    File "socket_send_receive.py", line 21, in main
      client()
    File "socket_send_receive.py", line 14, in client
      sock.connect(('127.0.0.1', 12345))
    File "&lt;string&gt;", line 1, in connect
  socket.error: [Errno 111] Connection refused
  Exception in thread Thread-1:
  Traceback (most recent call last):
    File "/home/cxuan/python/2.6/lib/python2.6/threading.py", line 532, in __bootstrap_inner
      self.run()
    File "/home/cxuan/python/2.6/lib/python2.6/threading.py", line 484, in run
      self.__target(*self.__args, **self.__kwargs)
    File "socket_send_receive.py", line 6, in server
      sock.bind(('127.0.0.1', 12345))
    File "&lt;string&gt;", line 1, in bind
  error: [Errno 98] Address already in use
  </code></pre>
  
  <p>I am looking for some insight into why this is happening and if it is possible to be genuinely resolved or what best practice should be adopted. </p>
  
  <p>I know already using this option can be a workaround thanks to the other posts here on stackoverflow.</p>
  
  <blockquote>
    <p>socket.SO_REUSEADDR</p>
  </blockquote>