#!/usr/bin/env python # # Written by Boudewijn Schoon. peer-to-peer@frayja.com # import asyncore, socket import optparse import time import os class AsynServer(asyncore.dispatcher): def __init__(self, port, opt): asyncore.dispatcher.__init__(self) self.create_socket(socket.AF_INET, socket.SOCK_STREAM) self.bind(('', port)) self.listen(100) if opt.prefix: self._path = opt.prefix else: self._path = "_%d.progress" % int(time.time()) self._id = 0 os.mkdir(self._path) def handle_accept(self): sock, addr = self.accept() self._id += 1 return AsynClient(sock, addr, "%s/progress.%d.raw"%(self._path, self._id)) class AsynClient(asyncore.dispatcher): def __init__(self, sock, addr, filename): asyncore.dispatcher.__init__(self, sock) self._io = open(filename, "w") print self._io.name, "--> open for:", addr def handle_close(self): print self._io.name, "--> close" self.close() def readable(self): return 1 def handle_read(self): self._io.write(self.recv(4096)) def writable(self): return 0 p = optparse.OptionParser() p.add_option("--prefix", help="Target directory. By default the current timestamp is in the name.", metavar="") opt, args = p.parse_args() if opt.prefix: if os.path.isdir(opt.prefix): print "prefix already exists!" raise SystemExit server = AsynServer(47771, opt) asyncore.loop()