0

This program cannot exit because the accept function blocks.

What can be done so that the program exits after a timeout even if the accept function is still running?

# taken from https://realpython.com/python-sockets/#echo-server

import socket

HOST = "127.0.0.1"  # Standard loopback interface address (localhost)
PORT = 65432  # Port to listen on (non-privileged ports are > 1023)

def connect ():
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
        s.bind((HOST, PORT))
        print("listening")
        s.listen()
        print("accepting")
        conn, addr = s.accept()             # If these lines are 
        with conn:                          # commented, the program
            print(f"Connected by {addr}")   # exits normally.
            while True:                     # This is why I think
                data = conn.recv(1024)      # that the *accept* function
                if not data:                # is the problem
                    break                   #
                conn.sendall(data)          #

def main():
    connect()

if __name__ == "__main__":
    main()
0

1 Answer 1

1

You can set a timeout on the server socket:

>>> import socket
>>> s=socket.socket()
>>> s.bind(('',5000))
>>> s.listen()
>>> s.settimeout(5)  # 5 seconds
>>> s.accept()                          # waits here...
Traceback (most recent call last):      # 5 seconds later...
  File "<stdin>", line 1, in <module>
  File "D:\dev\Python311\Lib\socket.py", line 294, in accept
    fd, addr = self._accept()
               ^^^^^^^^^^^^^^
TimeoutError: timed out

Catch time timeout if you want to implement other behavior. For example:

def accept(s):
    ''' Wait up to 5 seconds for connection.'''
    s.settimeout(5)
    try:
        results = s.accept()
    except TimeoutError:
        return None
    s.settimeout(None)  # disable timeout
    return results
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.