I'm trying to build a simple socket server in python:
import socket
import threading
import time
def handle(conn_addr):
print("Someone Connected")
time.sleep(4)
print("And now I die")
host = ''
port = 5000
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
s.bind((host,port))
except socket.error as e:
print(str(e))
s.listen(2)
while True:
threading.Thread(handle(s.accept())).start()
print("Should never be reached")
The socket server should accept multiple clients at the same time. I tried to test its functionality by calling telnet localhost 5000 from multiple tabs from my shell however the pattern that i get is
Someone Connected
And now I die
Someone Connected
And now I die
Instead of
Someone Connected
Someone Connected
Someone Connected
I call the telnet command within 4 seconds of each other so it should have 2 messages of connected in a row however the message is only returned after the previous socket is disconnected. Why is that and how could I go round fixing this?
-
1You are printing the die statement without closing the socket. The clients should still be connectedOneCricketeer– OneCricketeer2016年02月27日 16:00:47 +00:00Commented Feb 27, 2016 at 16:00
-
But why doesn't the function print "someone connected" as soon as I connect to it? It always waits for "die" to be printed ?Bula– Bula2016年02月27日 16:31:32 +00:00Commented Feb 27, 2016 at 16:31
-
As far as I can tell, it should print "connected", then pause for 4 seconds, then print "die" (even though you don't close the socket). Is that not what is happening?OneCricketeer– OneCricketeer2016年02月27日 16:37:13 +00:00Commented Feb 27, 2016 at 16:37
1 Answer 1
Its a classic mistake. You called handle() (which slept for 4 seconds) and then tried to create a thread from its result. The target should be a function reference and args should be passed separately.
threading.Thread(target=handle, args=(s.accept(),)).start()
In this version, the main thread waits for an accept and then creates the thread that runs handle.
2 Comments
Thread(target=mysock.rec, args=(1024,)).start() would be problematic. Where would the received data go to? recv may get anything from 0 to 1024 bytes (socket closed is 0, or since its byte oriented, only a partial message) and could get an Exception. I'd need the details to know. .... and that would be hard to put in a comment here. Perhaps a new question or maybe something on codereview.stackexchange.com?