[Python] How to error/exit a read operation that is blocked on a socket where there is no data

Discussão em 'Python' iniciado por Stack, Dezembro 7, 2024.

  1. Stack

    Stack Membro Participativo

    on some operating systems, when a socket is closed, the read operation errors, but on BSD it doesn't. This simple code works differently on different OS

    import socket
    import threading
    # Function to handle reading from the socket
    def read_from_socket(sock):
    while True:
    try:
    data = sock.recv(1024)
    if not data:
    continue
    print(f"Received data: {data}")
    except socket.error as e:
    print(f"Socket error: {e}")
    break
    print("Read thread exiting")
    # Create a socket and connect to a server
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.connect(('example.com', 80))
    print ("connected to socket")
    # Start the read thread
    read_thread = threading.Thread(target=read_from_socket, args=(sock,))
    read_thread.start()
    # Close the socket after some time
    import time
    time.sleep(20)
    print ("closing the socket")
    sock.close()
    print ("closed the socket")
    # Join the read thread to wait for its completion
    read_thread.join()
    print("Main thread exiting")


    what are the ways we can exit the read thread on BSD

    Continue reading...

Compartilhe esta Página