user1893187
user1893187

Reputation: 219

Multiple threads in Python server

I am building for school a little Python server script, that has to read a file and send it to the client.

Now, I need the server to answer to multiple requests from clients at same time. At this moment it will only accept 1 client... and just after the client is answered, it moves to the next.

My teacher told me to use multiple processes/threads to achieve that. I am new to Python so I have no idea how to manage this.

How can I do that?

Here is my code:

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
s.bind((host,port)) 
s.listen(backlog) 
while 1:
    print "server ready, waiting..."
    client, address = s.accept() 
    print "recvd client", address 
    data = client.recv(size) 
    if data:

        parametro_data = data.split(' ')
        if(parametro_data[0] == '/GET'):

            theFile = parametro_data[1].replace('\r\n','')

            if os.path.isfile(theFile):
                f = open(theFile, 'r')
                for line in f:
                    client.send(line)
                f.close()
            else:
                client.send("File not exists")

    client.close()

Upvotes: 1

Views: 840

Answers (2)

sean
sean

Reputation: 3985

To handle this in the model you have describe you will take out the code where you do the actual file sending and encapsulate this inside of a thread.

class HandleClient( threading.Thread ):
 def __init__( self, clientSocket, file_to_read ):
  ...setting up the thread object...
 def run( self ):
  ...sending code...

This will send the file so that your main acceptance thread will be able to handle other clients.

So, your client flow would be as follows:

new client connection -> accept the connection -> create the new thread object and call the start() method -> the thread will send the file to this client and then close the connection.

Threading Documentation

threading.Thread Documentation

I would also look into a thread pool as you can only have so many threads at once before it does not give you any benefit or if possible a framework that provides the server functionality and you just have to write the business logic, in your case the sending of the file.

Upvotes: 0

poke
poke

Reputation: 387647

What you should do is to keep the time the server thread is captured with a single request (i.e. after the s.accept() line returns) to a minimum. A common way to do that is to spawn a thread directly after that which then handles the request spearately. Then you can return to waiting for the next request (i.e. accept again) directly without being paused by the still ongoing handling which happens in the other thread.

I’d also suggest you to look into the socketserver module, as that already gives you exactly that in a higher level. You just define a handler for the connections, then create the server with that handler, and make the server “serve forever”.

Upvotes: 3

Related Questions