Issues with your account? Bug us in the Discord!

Python: Launching and probing the server

For the game I'm (re)making I'm using a client/server architecture, even for the sp mode. The client launches the server and attempts to see if a connection can be made before the client logs in. In linux everything works. In windows everything works, except socket.error is always raised. If the socket is made in a separate prompt, it connects fine.

So two questions:
a) Is there a better method for trying to do this?
b) If not, any ideas why it is failing in windows?

[code]
def launchSPServer(self):
if os.name == 'posix':
self.server = subprocess.Popen('python' +' ./Server.py', shell=True)
else:
self.server = subprocess.Popen('..\\python\\ppython.exe' +' Server.py')
self.server = True
import socket
x = True
serverSocket = socket.socket()
serverSocket.settimeout(0.25)
while x:
try:
#print 0
serverSocket.connect(('127.0.0.1', 1999))
x = False
#print 1
except socket.error:
pass
messenger.send('login')
print 'Server launched'
[/code]

Comments

  • BigglesBiggles <font color=#AAFFAA>The Man Without a Face</font>
    You've got a race condition. Welcome to the wonderful world of multi-process programming!

    What's probably happening is that after you execute subprocess.Popen(), the current process is getting first pick under Windows and executing first, running all the way down to its connect call, which then fails because the subprocess hasn't had a chance to execute enough to set up the listening socket. You need to add some synchronisation between the two processes. The easiest way to do this is to wait for a set message (like "ok" or something) from the child process's stdout in the parent process. When the child process has got its socket ready to go, it can write that message to its stdout. The parent process will get it and know the socket is ready to go, and can safely try to connect. Look at the [url=http://docs.python.org/library/subprocess.html#popen-objects]docs for Popen objects[/url] for info on how to set up its pipes.


    In an entirely separate tip: you don't need to check the OS and hard-code the interpreter's path. You can use sys.executable to get it. This will make your code more robust across different platforms and installation locations.
Sign In or Register to comment.