How to make server threads in Python?

0

Hello, I'm a beginner in Python and I'm creating a simple server but I can not create independent threads. When the client connects to the server it calls the worker function that waits for a client message to send a response. It turns out that only one connection is executed at a time and in the connection order, leaving the other clients who have already sent the message waiting.

while True:
    conn, address = ss.accept()
    print('DEBUG: Connected by ',  address)
    obj = threading.Thread(target = ServerWorker.worker(conn))
    obj.start()

Worker function:

def worker(conn):
    print('Running...')
    _in = conn.recv(1024)
    msg = _in.decode(encoding = 'utf-8')
    print('DEBUG: Processing ', msg, '...')
    msg = 'ECHO: ' + msg
    _out = conn.sendall(bytes(msg,encoding = 'utf-8'))
    conn.close()

I tried just calling another .py script instead of the thread but could not pass the conn object as an argument. Please help me.

    
asked by anonymous 04.11.2018 / 22:53

1 answer

0

In the way you are doing, you are calling the function ServerWorker.worker() first and then trying to start the thread with the result of that function (which in this case is None since it does not return anything). The parentheses force the function call to extract its result, before starting the thread. Your current code is equivalent to this:

resultado = ServerWorker.worker(conn)
obj = threading.Thread(target = resultado)

In fact, who will call the function is the threading module of python and not its code. You must pass the function without calling it yourself, that is, do not put the parentheses () after the function name, so you will be passing the function itself and not the result of it.

The parameters you want to pass to the target function must be passed in args and kwargs , so that the threading module can then pass them to its function when it is time, as it says at documentation :

obj = threading.Thread(target=ServerWorker.worker, args=[conn])

See that it should be passed an iterable with the positional parameters, in the example above was the [] list.

    
05.11.2018 / 00:28