# Updated by John Brearley, Jan 2013 # multiprocessing.connection client program import multiprocessing.connection,sys,time ;#,print_data # Get command line parameters, if any, for desired host & port. host="localhost" ;# default host argc=len(sys.argv) if (argc > 1): temp=sys.argv[1] temp=temp.strip() if (temp != ""): host=temp port=10500 ;# default port if (argc > 2): temp=sys.argv[2] temp=temp.strip() if (re.search("^\d+$",temp)): port=int(temp) ;# int() gives error on null string print("argc:",argc,"host:",host,"port:",port) # Create new client object print("\nConnecting to host:",host,"port:",port) cl=multiprocessing.connection.Client((host,port)) # print_data.print_data(cl) ;# for learning purposes # MUST use default client blocking mode! # Show socket info. # Fileno is unique only to this instance of python. # Fileno is often reused by other concurrently running python programs. # print("fileno:",cl.fileno()) # How to get getsockname() getpeername() ? # Process user input. while (1): cmd=input("cmd:") cmd=cmd.strip() # print("\ncmd:",cmd) if (cmd == "q"): time.sleep(0.2) cl.close() print("\nAll done!") break # Send cmd, wait for response. # NB: To force the server to become non-response, in the server window # type CTRL-S ("xoff") several times. This allows you to test the error # handling code below. # NB: sending a null byte string doesnt send anything to server. If you # turn off the cmd.strip and the if below, then you can send & receive # a single space or more. if (cmd != ""): timeout=1 cl.send(bytes(cmd,"ASCII")) # The for loop is intended for non-blocking operations. for i in range(16): # poll(x) waits for x seconds for input to be available before returning # This is how you deal with timeouts for a blocking client object. temp=cl.poll(1) print("i:",i,"before poll:",temp) if (temp): resp=cl.recv() print("i:",i,"resp:",resp) print("i:",i,"after poll:",cl.poll()) timeout=0 break else: time.sleep(0.2) if (timeout): print("ERROR: Timeout for cmd:",cmd)