VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > Python基础教程 >
  • Python3标准库:zlib GNUzlib压缩(3)

  •  
  • # Connect to the server as a client
  • logger.info('Contacting server on %s:%s', ip, port)
  • s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  • s.connect((ip, port))
  •  
  • # Ask for a file
  • requested_file = 'lorem.txt'
  • logger.debug('sending filename: %r', requested_file)
  • len_sent = s.send(requested_file.encode('utf-8'))
  •  
  • # Receive a response
  • buffer = BytesIO()
  • decompressor = zlib.decompressobj()
  • while True:
  • response = s.recv(BLOCK_SIZE)
  • if not response:
  • break
  • logger.debug('READ %r', binascii.hexlify(response))
  •  
  • # Include any unconsumed data when
  • # feeding the decompressor.
  • to_decompress = decompressor.unconsumed_tail + response
  • while to_decompress:
  • decompressed = decompressor.decompress(to_decompress)
  • if decompressed:
  • logger.debug('DECOMPRESSED %r', decompressed)
  • buffer.write(decompressed)
  • # Look for unconsumed data due to buffer overflow
  • to_decompress = decompressor.unconsumed_tail
  • else:
  • logger.debug('BUFFERING')
  • to_decompress = None
  •  
  • # deal with data reamining inside the decompressor buffer
  • remainder = decompressor.flush()
  • if remainder:
  • logger.debug('FLUSHED %r', remainder)
  • buffer.write(remainder)
  •  
  • full_response = buffer.getvalue()
  • lorem = open('lorem.txt', 'rb').read()
  • logger.debug('response matches file contents: %s',
  • full_response == lorem)
  •  
  • # Clean up
  • s.close()
  • server.socket.close()
  • 我们人为的将这个代码清单做了一些划分,以展示缓冲行为,如果将数据传递到compress()或decompress(),但没有得到完整的压缩或未压缩输出块,此时便会进行缓冲。

    客户连接到套接字,并请求一个文件。然后循环,接收压缩数据块。由于一个块可能未包含足够多的信息来完全解压缩,所以之前接收的剩余数据将与新数据结合,并且传递到解压缩器。解压缩数据时,会把它追加到一个缓冲区,处理循环结束时将与文件内容进行比较。

    
    相关教程
    关于我们--广告服务--免责声明--本站帮助-友情链接--版权声明--联系我们       黑ICP备07002182号