Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python socket object accept time out

Tags:

python

sockets

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 accepting and tending and passing them to a queue for the main thread. Right now I'm trying to get the child thread to interrupt so it can deconstruct appropriately. I think it is possible for me to just simply stop the child thread and have the parent deconstruct the child, but there are other times where I want to be able to return early form accept so I just decided that would be the most useful approach.

So, is there a way that I can have a time out or cancel the accept method so the thread can return w/o having something connect to it first?

like image 240
Narcolapser Avatar asked Sep 08 '11 21:09

Narcolapser


People also ask

What does socket timeout to Python?

Socket connection timeout High A new Python socket by default doesn't have a timeout. Its timeout defaults to None. Not setting the connection timeout parameter can result in blocking socket mode. In blocking mode, operations block until complete or the system returns an error.

How do I increase the socket timeout in Python?

The typical approach is to use select() to wait until data is available or until the timeout occurs. Only call recv() when data is actually available. To be safe, we also set the socket to non-blocking mode to guarantee that recv() will never block indefinitely.

How do you fix timeout error in Python?

In Python, use the stdin. readline() and stdout. write() instead of input and print. Ensure that the input value to test cases is passed in the expected format.

Does socket timeout close socket?

A socket read timeout does not kill the connection. It just causes a SocketTimeoutException. Whether the connection is still usable is a decision the application has to make.


1 Answers

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 = False
while not stopped:
  try: 
    (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 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.)

like image 98
fuenfundachtzig Avatar answered Sep 18 '22 14:09

fuenfundachtzig