Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python
- from twisted.internet import protocol, reactor, endpoints
- import datetime
- import os
- # set each file to be 20 Mb
- file_size = 20000000
- base_folder = "/home/marius/twisted-data/"
- class DataProtocol(protocol.Protocol):
- def __init__(self, addr):
- self.addr = addr
- # which chunk part we're at
- self.count = 0
- # check how much bytes we've written to the current file
- self.bytes_written = 0
- self.fp = None
- def dataReceived(self, data):
- # the amount of data received
- bytes_remaining = len(data)
- while bytes_remaining > 0:
- # we don't have an open fp, so we need to set up a new
- if not self.fp:
- self.bytes_written = 0
- self.count += 1
- self.fp = open(os.path.join(base_folder, "%s%d-%d" % (self.addr.host, self.addr.port,
- self.count)), 'wb')
- # we can write the whole chunk to file and there's still room
- if self.bytes_written + bytes_remaining < file_size:
- self.fp.write(data)
- self.bytes_written += bytes_remaining
- break
- # we can fill the file, so close it and reset counters
- elif self.bytes_written + bytes_remaining == file_size:
- self.fp.write(data)
- self.fp.close()
- self.fp = None
- break
- # we can't fit everything in the file
- else:
- available = file_size - self.bytes_written
- self.fp.write(data[0:available])
- self.fp.close()
- self.fp = None
- bytes_remaining =- available
- class DataFactory(protocol.Factory):
- def buildProtocol(self, addr):
- return DataProtocol(addr)
- endpoints.serverFromString(reactor, "tcp:1234").listen(DataFactory())
- reactor.run()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement