How to close connection when time expires in socket python?

Viewed 12

I have a following problem.

import socket 

HOST = "127.0.0.1"  #
PORT = 3999  # vetsi nez 1024, doporucoval na proseminari


with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: #
    s.bind((HOST, PORT)) 
    s.listen() 
    conn, addr = s.accept()
    s.settimeout(1.0)
    with conn:
        print(f"Connected by {addr}")

        while True: 
            import time
            start = time.time()

            received = conn.recv(1024)
            end = time.time()

            if not recieved:
                print(f"I was waiting {end-start} - it is 4 seconds, not 1!")


            print(f"I got '{received}'")

I would like to close the connection if conn.recv(1024) did not get anything within one second. How can I do it please? I tried import socket.timeout as TimeoutException as recommended here: Python: fixed wait time for receiving socket data but it seems to be outdated answer. Thanks

0 Answers
Related