如何在客户端完成之前保持Python服务器连接处于打开状态?

时间:2011-04-03 22:55:35

标签: python sockets networking

我有一个标准的分支TCPServer设置,它接收传入的请求并将文件发送回客户端。服务器似乎正在发送所有数据,但我检查了客户端收到的字节数!=发送的字节数。

经过进一步调查后,接收方法客户端表明服务器提前关闭了连接 - 导致接收失败。

然后我在发送文件后将服务器修改为休眠几秒钟 - 保持套接字打开足够长的时间以便客户端接收然后关闭它。这是有效的,但在我看来这是非常hackish,因为在关闭套接字之前很难预测线程应该睡多长时间。

我已尝试设置SO_LINGER服务器端以保持连接活动,但它没有帮助 - 即使我认为它应该。

必须有更好的方法来阻止客户端完全接收文件。在客户端收到所有数据之前,我需要做些什么来保证套接字不会关闭?

服务器

class ForkingTCPRequestHandler(SocketServer.BaseRequestHandler):
    def createSPP(self, dataLen, success):
        SPPStruct = struct.Struct('I?')
        values = (socket.htonl(dataLen), success,)
        packed_data = SPPStruct.pack(*values)       
        return packed_data

    def handle(self):
         """Enabling SO_LINGER to keep connection alive doesn't help"""
        self.request.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER, struct.pack('ii', 1, 5))

        """Send a packet to the client so it knows the length of incoming data""" 
        spp = self.createSPP(os.path.getsize(FILE_NAME), 1)
        self.request.sendall(spp)

        """Sending the file, finish() is automatically called after this.""" 
        f = open(FILE_NAME, 'rb')
        fileData = f.read()
        self.request.sendall(fileData)
        f.close()

    def finish(self):
        """Sleep until the file is fully received by the client.
        Sleeping keeps the connection open. BaseRequestHandler automatically
        closes the connection when finish() returns. This works but is not a
        robust solution."""
        time.sleep(5)

class ForkingTCPServer(SocketServer.ForkingMixIn, SocketServer.TCPServer):
    pass

if __name__ == '__main__':  
    try:
        server = ForkingTCPServer((HOST, PORT), ForkingTCPRequestHandler)
    except socket.error as e:
        sys.exit(1)

    try:
        server.serve_forever()
    except KeyboardInterrupt:
        server.shutdown()
        sys.exit(0)

客户端连接到服务器

    // Establishes a standard TCP connection
    memset(&targetAddr, 0, sizeof(targetAddr));
    targetAddr.sin_family = AF_INET;
    targetAddr.sin_port = htons(atoi(port));
    bcopy(hostdetails->h_addr, (char *)&targetAddr.sin_addr, hostdetails->h_length);

    sock = socket(AF_INET, SOCK_STREAM, 0);
    if (socket < 0) {
            return -1;
    }

    rc = connect(sock, (struct sockaddr *)&targetAddr, sizeof(targetAddr));
    if (rc < 0) {
            close(sock);
            return -1;
    }

客户端接收

    // Receiving spp (server side) known as symProcPacket (client side)
    // symProcPacket contains the length of the file that will be sent next
    // Receiving this packet is always successful
    typedef struct SymProcessPacket {
        u_int32_t totalDataLen;
        BOOL processingSuccessful;
    } SymProcessPacket;

    tempBuf = (char *)malloc(sizeof(SymProcessPacket)); 
    recvBytes = recv(s, tempBuf, sizeof(SymProcessPacket), 0);
    if (recvBytes < 0) {
        goto processingError;       
    }

    memcpy(&symProcPacket, tempBuf, sizeof(SymProcessPacket));
    free(tempBuf);

    // Receiving the file
    // Receive chunks and put in a buffer until entire file is received
    tempBuf = (char*) malloc(sizeof(char)*ntohl(symProcPacket.totalDataLen));
    totalRecv = 0;
    recvBytes = 0;

    while (totalRecv < ntohl(symProcPacket.totalDataLen)) {
        recvBytes = recv(sock, tempBuf+totalRecv, (1<<14), 0);
        if (recvBytes < 0) {
            // RecvBytes returns -1, which is an error before getting all the data
            // It gets a "Connection was reset by peer" error here, unless the server
            // sleeps for a bit. It means the server closed the connection early.
            printf("Error: %s", errtostr(errno));
            goto errorImporting;
        }
        totalRecv += recvBytes;
    }

2 个答案:

答案 0 :(得分:1)

我正在跳过你的代码部分。我会专注于你的问题,收到完整的文件。一种很酷的方式是采用HTTP方式。首先,只发送您要发送的字节数,以便接收端将从套接字接收到该数量。因此,只需向接收器发送少量额外数据即可完成工作..

发件人:

  • 发送要发送的文件的大小
  • 发送文件数据

接收器:

  • 接收文件大小
  • 接收数据,直到len(data)== size_received

答案 1 :(得分:0)

我无法弄清楚为什么睡觉已经解决了什么。

但我认为python在发送5个字节和C ++时读取8个字节。在python中?接受字节。 BOOL我认为将typedefed作为一个int并占用大约4个字节。

一般来说,不鼓励对套接字进行读/写结构。