Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #1/usr/bin/env python
- # this is from The Python
- # Standard Library by example
- # ISBN13: 9780321767349
- import zlib
- import logging
- import SocketServer
- import binascii
- BLOCK_SIZE = 64
- class ZlibRequestHandler(SocketServer.BaseRequestHandler):
- logger = logging.getLogger('Server')
- def handle(self):
- compressor = zlib.compressobj(1)
- # Find out what file the client wants
- filename = self.request.recv(1024)
- self.logger.debug('client asked for: "%s"', filename)
- # Send chunks of the file as they are compressed
- with open(filename, 'rb') as input:
- while True:
- block = input.read(BLOCK_SIZE)
- if not block:
- break
- self.logger.debug('RAW "%s"', block)
- compressed = compressor.compress(block)
- if compressed:
- self.logger.debug('SENDING "%s"',
- binascii.hexlify(compressed))
- self.request.send(compressed)
- else:
- self.logger.debug('BUFFERING')
- # Send any data being buffered by the compressor
- remaining = compressor.flush()
- while remaining:
- to_send = remaining[:BLOCK_SIZE]
- remaining = remaining[BLOCK_SIZE:]
- self.logger.debug('FLUSHING "%s"',
- binascii.hexlify(to_send))
- self.request.send(to_send)
- return
- if __name__ == '__main__':
- import socket
- import threading
- from cStringIO import StringIO
- logging.basicConfig(level=logging.DEBUG,
- format='%(name)s: %(message)s',
- )
- logger = logging.getLogger('Client')
- # Set up a server, running in a seperate thread
- address = ('localhost', 0) # let the kernel assign a port
- server = SocketServer.TCPServer(address, ZlibRequestHandler)
- ip, port = server.server_address # what port was assigned?
- t = threading.Thread(target=server.serve_forever)
- t.setDaemon(True)
- t.start()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement