0

Using sockets, the below Python code opens a port and waits for a connection. Then, it sends a response when a connection is made.

import socket
ip = 127.0.0.1
port = 80
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((ip, port))
s.listen(1)
conn, addr = s.accept()
conn.send(response)
conn.close()

If a connection is not established within 10 seconds, I would like it to move on. Is there a way to define a timeout for s.accept()?

  s.accept(timeout=10)

Maybe something like the above line?

Thanks in advance for your help!

2 Answers 2

1

to set a timeout for socket s before you connect listen do s.settimeout(10)

edit

I assume it works when listening

Sign up to request clarification or add additional context in comments.

Comments

0

Use socket.settimeout:

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(10)

timeout = False
while not timeout:
  try: 
    (conn, addr) = s.accept() 
  except socket.timeout:
    pass
  else:
    # your code

To make a 10 second timeout the default behavior for any socket, you can use

socket.setdefaulttimeout(10)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.