THRIFT-3682 Do not reuse refused sockets in test scripts
Client: Test
Patch: Nobuaki Sukegawa

This closes #902
diff --git a/test/crossrunner/run.py b/test/crossrunner/run.py
index 4b4eb0a..2c212e0 100644
--- a/test/crossrunner/run.py
+++ b/test/crossrunner/run.py
@@ -129,11 +129,16 @@
     def ensure_socket_open(proc, port, max_delay):
         sleeped = 0.1
         time.sleep(sleeped)
-        sock4 = socket.socket()
-        sock6 = socket.socket(family=socket.AF_INET6)
         sleep_step = 0.2
-        try:
-            while sock4.connect_ex(('127.0.0.1', port)) and sock6.connect_ex(('::1', port)):
+        while True:
+            # Create sockets every iteration because refused sockets cannot be
+            # reused on some systems.
+            sock4 = socket.socket()
+            sock6 = socket.socket(family=socket.AF_INET6)
+            try:
+                if sock4.connect_ex(('127.0.0.1', port)) == 0 \
+                        or sock6.connect_ex(('::1', port)) == 0:
+                    return True
                 if proc.poll() is not None:
                     logger.warn('server process is exited')
                     return False
@@ -142,11 +147,11 @@
                     return False
                 time.sleep(sleep_step)
                 sleeped += sleep_step
-            logger.debug('waited %f sec for server port open' % sleeped)
-            return True
-        finally:
-            sock4.close()
-            sock6.close()
+            finally:
+                sock4.close()
+                sock6.close()
+        logger.debug('waited %f sec for server port open' % sleeped)
+        return True
 
     try:
         max_bind_retry = 3
diff --git a/test/py/RunClientServer.py b/test/py/RunClientServer.py
index d4a9cb2..15c4d2b 100755
--- a/test/py/RunClientServer.py
+++ b/test/py/RunClientServer.py
@@ -133,20 +133,26 @@
                             % (server_class, ' '.join(server_args)))
 
     # Wait for the server to start accepting connections on the given port.
-    sock = socket.socket()
     sleep_time = 0.1  # Seconds
     max_attempts = 100
-    try:
-        attempt = 0
-        while sock.connect_ex(('127.0.0.1', port)) != 0:
+    # try:
+    attempt = 0
+    while True:
+        sock4 = socket.socket()
+        sock6 = socket.socket(socket.AF_INET6)
+        try:
+            if sock4.connect_ex(('127.0.0.1', port)) == 0 \
+                    or sock6.connect_ex(('::1', port)) == 0:
+                break
             attempt += 1
             if attempt >= max_attempts:
                 raise Exception("TestServer not ready on port %d after %.2f seconds"
                                 % (port, sleep_time * attempt))
             ensureServerAlive()
             time.sleep(sleep_time)
-    finally:
-        sock.close()
+        finally:
+            sock4.close()
+            sock6.close()
 
     try:
         if verbose > 0: