# server.py # Simple non-object way to run server with multiple connetions and handle commands # Sky Coyote for SWRI 2007 # Import modules used import os import socket from PyQt4 import QtCore, QtGui import plotimage # Must have this to keep Python references to Qt objects, or they will disappear! windowlist = [] # Timer timout: handle socket commands def timeout(): # Refer to vars in enclosing scope global app, c, sessions, count # Look for a socket command c.setblocking(0) try: # Peek for command without removal data = c.recv(1024, 2) except: # Return if no data or other error return # Get and remove data c.setblocking(1) data = c.recv(1024) count += 1 print str(sessions) + ':' + str(count) + ': ' + data # Close socket session and kill PyQt app if data.upper().startswith('CLOSE'): c.send(str(sessions) + ':' + str(count) + ': ' + 'Connection closing') c.close() os._exit(0) # Plot a file in a new window elif data.upper().startswith('PLOTFILE'): fname = data.split()[1] c.send(str(sessions) + ':' + str(count) + ': ' + 'Plotting ' + fname) min = max = -1 # Create new image window using previously defined class imageViewer = plotimage.ImageViewer(sessions, fname, min, max) # Add Qt data to Python list, or it will vanish! windowlist.append(imageViewer) imageViewer.show() else: c.send(str(sessions) + ':' + str(count) + ': (Unknown command) ' + data) # Main program start # Create a socket and set it to reuse addresses, or bind() may fail s = socket.socket() s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # Bind socket to port host = socket.gethostname() port = 1234 s.bind((host, port)) # Look for connections sessions = 0 s.listen(5) while True: # Get a new connection c, addr = s.accept() sessions += 1 # Fork another Python process if os.fork() == 0: count = 0 print str(sessions) + ':' + str(count) + ': ' + 'Got connection from', addr c.send(str(sessions) + ':' + str(count) + ': ' + 'Connected') # Create new PyQt app app = QtGui.QApplication([]) # Create timer to handle incoming socket commands timer = QtCore.QTimer() QtCore.QObject.connect(timer, QtCore.SIGNAL("timeout()"), timeout) timer.start(500) # Run GUI app.exec_() c.close() os._exit(0)