1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121
| """ This will only spawn one gtk application at a time. If this command is executed while an instance is already running, the command line arguments are sent to the already running application. """ import sys import pygtk pygtk.require('2.0') import gtk import socket import threading import SocketServer class ThreadedTCPRequestHandler(SocketServer.BaseRequestHandler): def handle(self): data = self.request.recv(1024) cur_thread = threading.currentThread() self.server.app.label.set_label(data) response = 'string length: %d' % len(data) print 'responding to',data,'with',response self.request.send(response) class ThreadedTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer): stopped = False allow_reuse_address = True def serve_forever(self): while not self.stopped: self.handle_request() def force_stop(self): self.server_close() self.stopped = True self.create_dummy_request() def create_dummy_request(self): client(self.server_address[0], self.server_address[1], 'last message for you') def client(ip, port, message): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((ip, port)) sock.send(message) response = sock.recv(1024) print "Received: %s" % response sock.close() def start_server(host, port): server = ThreadedTCPServer((host, port), ThreadedTCPRequestHandler) ip, port = server.server_address server_thread = threading.Thread(target=server.serve_forever) server_thread.setDaemon(True) server_thread.start() return server class SingleInstanceApp: def destroy(self, widget, data=None): self.server.force_stop() gtk.main_quit() def __init__(self, server): self.server = server self.window = gtk.Window(gtk.WINDOW_TOPLEVEL) self.window.set_default_size(300,30) self.window.connect("destroy", self.destroy) self.label = gtk.Label("hello world") self.window.add(self.label) self.window.show_all() self.window.show() def main(self): gtk.gdk.threads_init() gtk.main() if __name__ == "__main__": HOST, PORT = "localhost", 50010 server = None try : client(HOST, PORT, ' '.join(sys.argv)) print 'an insance was already open' except socket.error : exceptionType, exceptionValue, exceptionTraceback = sys.exc_info() if exceptionValue[0] == 111 : print 'this is the first instance' server = start_server(HOST, PORT) else : raise app = SingleInstanceApp(server) server.app = app app.main()
|