Python Socket Object Accept Time Out
Question: Is there some sort of time out or interrupt to the socket.accept() function in python? Info: I have a program that has a child thread bound to a port and constantly acce
Solution 1:
You can use settimeout()
as in this example:
import socket
tcpServer = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
tcpServer.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
tcpServer.settimeout(0.2) # timeout for listening
tcpServer.bind(('0.0.0.0', 10000)) # IP and PORT
tcpServer.listen(1)
stopped = Falsewhilenot stopped:
try:
(conn, (ip, port)) = tcpServer.accept()
except socket.timeout:
passexcept:
raiseelse:
# work with the connection, create a thread etc.
...
The loop will run until stopped
is set to true and then exit after (at most) the timeout you have set. (In my application I pass the connection handle to a newly created thread and continue the loop in order to be able to accept further simultaneous connections.)
Solution 2:
You can set the default timeout with
import socket
print socket.getdefaulttimeout()
socket.setdefaulttimeout(60)
AFAIK This will affect all the socket operation
Solution 3:
Maybe settimeout() is what you're looking for.
Post a Comment for "Python Socket Object Accept Time Out"