import sys import os import subprocess import time import socket import errno host, port = "localhost", 4000 if os.environ.get("__SRV__", None): # This is the server try: time.sleep(5) # Listen family, socktype, proto, canonname, sockaddr =\ socket.getaddrinfo(host, port, socket.AF_INET, socket.SOCK_STREAM)[0] sock = socket.socket(family, socktype) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.setblocking(False) sock.bind(sockaddr) sock.listen(5) while 1: time.sleep(0.3) try: clientSock, addrInfo = sock.accept() except socket.error as e: if e.errno == errno.EWOULDBLOCK or e.errno == errno.EAGAIN: continue raise print "Server: A client connected" break except Exception as e: print "SERVER exception:\n%s" % e else: # This is the client try: # Spawn server proc = subprocess.Popen([sys.executable, "-m", "conntest"], env = { "__SRV__" : "1" }, shell = False) # Try to connect to server family, socktype, proto, canonname, sockaddr =\ socket.getaddrinfo(host, port, socket.AF_INET, socket.SOCK_STREAM)[0] sock = socket.socket(family, socktype) while 1: time.sleep(0.3) try: sock.connect(sockaddr) except (OSError, socket.error) as e: if e.errno == errno.ECONNREFUSED: sys.stdout.write(".") sys.stdout.flush() continue if e.strerror.endswith("java.nio.channels.CancelledKeyException"): print "CLIENT: Should not happen: CancelledKeyException" print e continue raise break print "\nClient: Connected to server" proc.wait() except Exception as e: print "CLIENT exception:\n%s" % e