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()
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.acceptagain) 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”.