Python socket object timeout

Question: Is there some kind of timeout or interruption of socket.accept () function in python?


information:

I have a program that has a child thread mapped to a port, and constantly receives and processes and queues them for the main thread. Right now, I'm trying to get a thread interrupt to be interrupted so that it can deconstruct properly. I think it’s easy for me to simply stop the child flow and the parent to deconstruct the child, but there are other cases when I want to be able to return to the early form, so I decided that this would be the most useful approach.

So, is there a way I can have a timeout or cancel the accept method so that the thread can return without connecting to something?

+7
source share
3 answers

You can set a default timeout with

import socket print socket.getdefaulttimeout() socket.setdefaulttimeout(60) 

AFAIK This will affect all socket operation

+8
source

Perhaps settimeout () is what you are looking for.

+6
source

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.bind(('0.0.0.0', 10000)) # IP and PORT stopped = False while not stopped: try: tcpServer.settimeout(0.2) # timeout for listening tcpServer.listen(1) (conn, (ip, port)) = tcpServer.accept() except socket.timeout: pass except: raise else: # work with the connection, create a thread etc. ... 

The loop will run until stopped is set to true and then exits after (at most) the timeout you set. (In my application, I pass the connection descriptor to the newly created thread and continue the loop to be able to accept additional concurrent connections.)

+2
source

All Articles