I'm using sockets for the first time in Python, and I have a problem.
I have a threaded request handler for my UDP server, but because of the way it works (as suggested here) I can't figure out how to pass arguments to it. I need it to access other objects in the application, because it must notify them of the actions performed by the different clients in the network. However the class representing the handler cannot be instantiated, so it can't take arguments via the constructor.
This is a simplified version of my code.
class ThreadedUDPRequestHandler(socketserver.BaseRequestHandler):
def handle(self):
data = self.request[0].strip()
socket = self.request[1]
print ("{} wrote:".format(self.client_address[0]))
print (data)
#Ideally, I'd call a method of an object here
class ThreadedUDPServer(socketserver.ThreadingMixIn, socketserver.UDPServer):
pass
class ServerManager():
def __init__(self, player_box):
self.player_box = player_box
HOST, PORT = "xxx.xxx.xxx.xxx", 9999
self.server = ThreadedUDPServer((HOST, PORT), ThreadedUDPRequestHandler)
ip, port = self.server.server_address
def start(self):
server_thread = threading.Thread(target=self.server.serve_forever)
server_thread.start()
def stop(self):
self.server.shutdown()
In this case, the object I'd like the request handler to access is player_box. The goal is to call a method of that object every time a request is made. Is there a way to do this, or should I use a different approach?
I noticed there is a similar question here, but the proposed solution does not work at all for me. In fact, it doesn't make much sense to me...
s/ed/ing/. See source