Dan Alexander
Dan Alexander

Reputation: 2072

Python Socket - Use Client in Seperate Function

I am developing a basic server login system which I can use for almost anything, the problem is when you define clients like for example:

client, address = socket.accept()
data = client.recv(1024)
print(data)

So you can easily do this but what I want to do it something like this:

def clientPrint(client):
    while 1:
        data = client.recv(1024)
        print(data)
while 1:
    client, address = socket.accept()
    Thread(target=clientPrint, args=(client)).start()

So as you can see I want to use the client in another function but then I get this error:

Exception in thread Thread-1:
Traceback (most recent call last):
  File "C:\Python34\lib\threading.py", line 920, in _bootstrap_inner
    self.run()
  File "C:\Python34\lib\threading.py", line 868, in run
    self._target(*self._args, **self._kwargs)
TypeError: clientRecv() argument after * must be a sequence, not socket

This was just a rough idea of what I want to do, so is there anyway I can use a socket client in a function like how I wanted it? If someone could find me a solution to this I would be very greatful! If you need more code to get a better idea of what I want just ask in a comment and I will add it. I have already looked all over for something like this but sadly I haven't found anything.

Thanks in advance!

Upvotes: 0

Views: 513

Answers (1)

Zacrath
Zacrath

Reputation: 556

The problem is that in the last line:

Thread(target=clientPrint, args=(client)).start()

(client) does not create a tuple. To create a tuple with a single item you need to change it to (client,)

It is actually the comma that makes tuples. (Except for the special empty tuple syntax: ()) For example, this makes a tuple:

seq = 1, 2, 3

Trailing commas are also allowed, which is how you make a tuple with a single element.

seq = 1,

The parentheses are only there so that python doesn't think the comma is an argument separator.

Tuples and Sequences

Upvotes: 1

Related Questions