So I have two very simple python scripts that communicate over a socket. Right now they are both running on the same windows PC.
Here's controller.py:
import socket
import time
import sys
from subprocess import Popen, CREATE_NEW_CONSOLE
HOST = '192.168.1.107' # The remote host
PORT = 50557 # The same port as used by the server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
s.connect((HOST, PORT))
except:
Popen([sys.executable, 'driver.py'], creationflags=CREATE_NEW_CONSOLE)
time.sleep(0.2);
s.connect((HOST, PORT))
s.send(sys.argv[1])
data = s.recv(1024)
s.close()
print 'Received', repr(data)
And here's driver.py:
import socket
HOST = '' # Symbolic name meaning the local host
PORT = 50557 # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)
while 1:
print 'Waiting for controller connection.'
conn, addr = s.accept()
print 'Connected to ', addr
while 1:
data = conn.recv(1024)
print 'Recieved ', data
if not data: break
if data == 'Q': quit()
print 'A.'
conn.send(data[::-1])
print 'B.'
print 'C.'
conn.close()
If I open two cmd
windows and python <filename>.py <arg>
them both everything works fine. I can leave driver.py
running and run controller.py
over and over again. Until I kill the driver by sending a "Q".
The try/except statement opens up a new window and runs driver.py
if the connection can't be made. Theoretically this just makes sure that the receiver is running before it sends anything. This ALMOST works but for some reason driver.py
hangs inside the second while loop for reasons I cannot explain. Here's the output from sequential controller.py
calls:
Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation. All rights reserved.
>python controller.py FirstMsg
Received 'gsMtsriF'
>python controller.py SecondMsg
Received 'gsMdnoceS'
>python controller.py Q
Received ''
>python controller.py ThirdMsg
Received 'gsMdrihT'
>python controller.py FourthMsg
(After FourthMsg controller.py
hangs forever)
Here's the output from driver.py
Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation. All rights reserved.
>python driver.py
Waiting for controller connection.
Connected to ('192.168.1.107', 49915)
Recieved FirstMsg
A.
B.
Recieved
C.
Waiting for controller connection.
Connected to ('192.168.1.107', 49916)
Recieved SecondMsg
A.
B.
Recieved
C.
Waiting for controller connection.
Connected to ('192.168.1.107', 49917)
Recieved Q
(Whereupon it returns to the regular command prompt.) The new window created with Popen contains this: Waiting for controller connection. Connected to ('192.168.1.107', 49918) Recieved ThirdMsg A. B.
So in the weird new window (which I just noticed does not look or act like a regular cmd window) the program seems to hang on data = conn.recv(1024)
.
Why does driver.py
act differently in the new window, and how can I fix it?