4

I'm trying to passing some parameter to the server tread, but I have no idea how?

this is my code:

HOST, PORT = socket.gethostbyname( socket.gethostname() ), 31000
self.server = SocketServer.ThreadingTCPServer( ( HOST, PORT ), MCRequestHandler )
ip, port = self.server.server_address        
self.server_thread = threading.Thread( target = self.server.serve_forever )

this is the MCRequestHandler

class MCRequestHandler( SocketServer.BaseRequestHandler ):

    global Lidars, clientsLock, postbox
    Lidars = []
    postbox = {}
    clientsLock = threading.RLock()    

    def setup( self ):
        clientsLock.acquire()

How can I pass one or two parameter to the MCRequestHandler class?

1 Answer 1

3

I think the second parameter of ThreadingTCPServer is a factory:

  SocketServer.ThreadingTCPServer( ( HOST, PORT ), MCRequestHandler )

What you could do is your own factory here. Class will contstuct a callable object. when the object is called it will initialize MCRequestHandler with parameters given to the factory:

class MyRequestHandlerFactory(object):

  def __init__(self, param1, param2): 
            self.param1 = param1
            self.param2 = param2

  def __call__(self):
            handler = MCRequestHandler()
            handler.param1 = param1
            handler.param2 = param2

Then initialize:

  factory = MyRequestHandlerFactory("x", "y")
  SocketServer.ThreadingTCPServer( ( HOST, PORT ), factory)
Sign up to request clarification or add additional context in comments.

5 Comments

I did this, but get this error. TypeError: __call__() takes 1 positional argument but 4 were given. Does anyone know what could be the reason?
@bronco: try this signature def __call__(self, *args, **kwargs) and pass the args to the handler transparently: YourRequestHandler(*args, **kwargs)
If I do that I get ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host
@broncoAbierto: add return handler to the __call__.
@J.F. Sebastian Still complaining about the arg count (takes 3, 4 given). I find threading in this ServerSocket framework a little weird. I'm gonna go with Twisted, I think.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.