Python: SocketServer closes TCP connection unexpectedly

前端 未结 2 1065
谎友^
谎友^ 2021-01-06 06:55

I would like to implement a TCP/IP network client application that sends requests to a Python SocketServer and expects responses in return. I have started out with the offic

2条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-06 07:34

    The client is broken. It calls recv just once and then closes the connection without ensuring it has received everything the server had to send.

    The correct way to fix this depends on the protocol you are using, which you haven't explained. It's not apparent from the server code what the protocol for server to client "messages" is. What is the client supposed to expect to get from the server? The server, for example, expects a line from the client, a message marked with a newline to indicate the end of the line. So the server knows when it has received a message by checking for a newline. How is the client supposed to do it? Where is that code?

    I'll assume for the sake of argument that your protocol always uses messages and defines a message as terminated by a newline.

        request  = self.rfile.readline().strip()
    

    This reads a message because it calls readline.

    sent = sock.sendall(data + '\n')
    

    This sends a message because it sends a series of bytes terminated by a newline.

    received = sock.recv(1024)
    

    Oops, this just receives some bytes, not a message. There needs to be code to check if a newline was received and, if not, call recv again, otherwise, calling close will force an abnormal close of the socket (because the message was not, and can never be, received), which is precisely what you are seeing.

提交回复
热议问题