# Written by John Brearley, Jan 2013 import multiprocessing,multiprocessing.connection,socket,time # Routine handles new incoming sockets as a separate process. def handle_socket(s): print("handle_socket s:",s) conn=s.accept() # Plan was to launch another process instance of handle_socket here so that # the listener object always has someone watching for incoming sockets. # Then do recv/send echo of data on existing conn. # Simple client connects to server, sends data, receives data, then disconnects. def simple_client(host,port): # Connect to server if (host == ""): host="localhost" time.sleep(1) ;# delay to make sure server is listening print("simple_client connecting to host",host,"port",port) c=socket.socket(socket.AF_INET,socket.SOCK_STREAM) c.connect((host,port)) # Send data to server time.sleep(1) data=b"abcd" print("simple_client sending:",data) c.send(data) # Wait for server response print("simple_client waiting for data") resp=c.recv(1024) print("simple_client received:",resp) # Close connection time.sleep(1) print("simple_client closing") c.close() # Main program if (__name__ == "__main__"): # Create a new multiprocessing connection listener object port=10500 host="" s=multiprocessing.connection.Listener((host,port)) print("main server listening on host",host,"port",port) # Launch simple client as seperate process. cl=multiprocessing.Process(target=simple_client, args=(host,port));# create new process print("main created simple_client",cl) cl.start() ;# dont use obj.run(), run forces serial mode, not parallel! # When accept/recv/send is done by the main process that created the listener object, # there is no issue. conn=s.accept() print("main conn:",conn,"waiting for data") data=conn.recv() ;# Memory Error occurs here <<<================================================ print("main recv:",data) conn.send(data) exit() # Once the listener object works OK in the main process, the plan here is to # launch another simple client process followed by the handle_socket as another # process and let them talk to each other. # Launch another simple_client process. # Launch first independant process for listener. # NB: args=(...,) must have at least one comma! Even if only 1 arg! obj=multiprocessing.Process(target=handle_socket, args=(s,));# create new process print("main created first handle_socket process",obj) obj.start() ;# dont use obj.run(), run forces serial mode, not parallel! # Wait for children processes to terminate. while (1): time.sleep(1.0) children=multiprocessing.active_children() # print("children:",children) if (len(children) == 0): print("main no more children running.") break # End main program print("main all done.")