Reputation: 205
import threading
import socket
sock = socket.socket()
sock.bind(('0.0.0.0', 9999))
sock.listen(5)
def handle_client(sock_client):
data = sock_client.recv(4096)
while data:
sock_client.send("this is server: " + data)
data = sock_client.recv(4096)
sock_client.close()
while True:
client = sock.accept()
t = threading.Thread(target=handle_client, args=client)
t.start()
TypeError: handle_client() takes exactly 1 argument (2 given)
this Why, my thread args only give a parameter, why tell me to give two parameters.
how to understand this?
Upvotes: 0
Views: 2864
Reputation: 2888
You're calling threading function in the wrong way. Currently, You use this:
t = threading.Thread(target=handle_client, args=client)
However, You should use this:
t = threading.Thread(target=handle_client, args=(client, ))
If You read the docs, You'll see that args
parameter should be a tuple, and not a single variable.
Update:
Just tested my code, it works fine. Yes, program will still raise an error (AttributeError: 'tuple' object has no attribute 'recv'
), but this is because You should use sock_client[0]
to receive data (sock_client
itself is a tuple consisting of connection object and address).
So, proper code is here:
import threading
import socket
sock = socket.socket()
sock.bind(('0.0.0.0', 9999))
sock.listen(5)
def handle_client(sock_client):
conn = sock_client[0]
address = sock_client[1]
data = conn.recv(4096)
while data:
conn.send("this is server: " + data)
data = conn.recv(4096)
conn.close()
while True:
client = sock.accept()
t = threading.Thread(target=handle_client, args=(client, ))
t.start()
Upvotes: 3