[Python] Confused about python sockets

Discussão em 'Python' iniciado por Stack, Junho 23, 2025.

  1. Stack

    Stack Membro Participativo

    I have 2 python programs: 1st one is a tcp server that in while True cycle accepts new clients and handles each of them in a separate thread. On the client side I have basic functionality and use it for sending and receiving simple messages. The thing that I don't understand - it is how I can close client socket properly.

    For now I'm using this code to close my client socket:

    def __on_s_close(self):
    try:
    self.__socket.shutdown(socket.SHUT_RDWR)
    except socket.error as e:
    logger.error(f"error while shutting down: {e}")
    finally:
    self.__socket.close()
    self.__socket = None
    logger.debug("client terminated from client module!")


    As I understood, in the Server module I accept a client socket object, so I can shutdown and close it from the server side. My questions are:

    1. Where do I need to close the client socket - in the server module or in client module? What's the difference?
    2. If I close it in server module, what happens to the socket object in the client module? It becomes None Type? Or stays the same?
    3. If I want reconnect client to the server, do I need to create a new instance of a socket class, or I can use previous one?
    4. What happens after socket.close()? Also, as I understood, even after I executed this method on the client side, due to while True cycle my program still can reach socket.recv() function and run into errors. But when I execute socket.close() on the server side - I don't get such error on the client side. Is there any way to close socket gracefully on the client side?(excluding try/except)

    Thank you for your help.

    Continue reading...

Compartilhe esta Página