Changing your handler to
class SingleTCPHandler(SocketServer.BaseRequestHandler):
""" One instance per connection. """
def __init__(self, callback, *args, **keys):
self.callback = callback
SocketServer.BaseRequestHandler.__init__(self, *args, **keys)
def handle(self):
data = Net.recv_from_socket(self.request)
self.callback(data)
Somewhere later (where you create the TCP Server):
def show_message_box(data):
GUI.run(str("RECV'd message: %s" % data))
def handler_factory(callback):
def createHandler(*args, **keys):
return ThreadedTCPRequestHandler(callback, *args, **keys)
return createHandler
server = ThreadedTCPServer((HOST, PORT), handler_factory(show_message_box))
Explanation:
1) handler_factory is called with the callback which should be invoked.
2) handler_factory creates a new function called createHandler. This function will be handed over to ThreadedTCPServer. It invokes it when it needs to create a new handler.
3) When invoked, it creates your ThreadedTCPRequestHandler and hands over the callback parameter (which is show_message_box in this example) to ThreadedTCPRequestHandler.init which stores it. The "magic" behind this is called a "closure". I.e. you can access the callback parameter from the outer function handler_factory within the inner function createHandler. Google for "closure python" and you will get some good explanations.
4) When handle() is finally invoked, it calls self.callback(data). Since self.callback is show_message_box, show_message_box(data) will be called effectively.
There are slightly shorter ways to express this as well:
def my_callback():
print 'Hello'
server = ThreadedTCPServer((HOST, PORT), lambda *args, **keys: ThreadedTCPRequestHandler(my_callback, *args, **keys))
will work, just as
def my_callback():
print 'Hello'
import functools
server = ThreadedTCPServer((HOST, PORT), functools.partial(ThreadedTCPRequestHandler, my_callback))
I don't know your specific use case, but if you need to do more stuff with sockets, you might want to look at http://www.twistedmatrix.com (popular python networking package). You should also be aware that a lot of GUI systems don't like to be run concurrently from multiple threads, so you need to watch out for this.