本文整理汇总了Python中BitTorrent.RawServer_twisted.RawServer.listen_forever方法的典型用法代码示例。如果您正苦于以下问题:Python RawServer.listen_forever方法的具体用法?Python RawServer.listen_forever怎么用?Python RawServer.listen_forever使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类BitTorrent.RawServer_twisted.RawServer
的用法示例。
在下文中一共展示了RawServer.listen_forever方法的7个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: main
# 需要导入模块: from BitTorrent.RawServer_twisted import RawServer [as 别名]
# 或者: from BitTorrent.RawServer_twisted.RawServer import listen_forever [as 别名]
def main(self):
"""\
Start the Mainline client and block indefinitely, listening for connectons.
"""
uiname = "bittorrent-console"
defaults = get_defaults(uiname)
config, args = configfile.parse_configuration_and_args(defaults, uiname)
config = Preferences().initWithDict(config)
data_dir = config['data_dir']
self.core_doneflag = DeferredEvent()
self.rawserver_doneflag = DeferredEvent()
rawserver = RawServer(config) #event and I/O scheduler
self.multitorrent = MultiTorrent(config, rawserver, data_dir) #class used to add, control and remove torrents
self.tick() #add periodic function call
rawserver.add_task(0, self.core_doneflag.addCallback, lambda r: rawserver.external_add_task(0, shutdown))
rawserver.listen_forever(self.rawserver_doneflag) # runs until the component terminates
self.send(producerFinished(self), "signal")
示例2: callable
# 需要导入模块: from BitTorrent.RawServer_twisted import RawServer [as 别名]
# 或者: from BitTorrent.RawServer_twisted.RawServer import listen_forever [as 别名]
## try:
## if callable(v):
## print v
## psyco.bind(v)
## count += 1
## except:
## pass
## print count
## if count > 0:
## break
rerun()
if stackless:
print 'stackless'
stackless.tasklet(lambda : rawserver.listen_forever())()
stackless.run()
else:
print 'stack'
rawserver.listen_forever()
n = 0
i = 0
def rerun2():
global i
global a
a[i] = time.clock()
i += 1
if i < n:
rerun2()
while n < m:
示例3: errorfunc
# 需要导入模块: from BitTorrent.RawServer_twisted import RawServer [as 别名]
# 或者: from BitTorrent.RawServer_twisted.RawServer import listen_forever [as 别名]
ef = lambda e: errorfunc(logging.WARNING, e)
platform.write_pid_file(config['pid'], ef)
t = None
try:
r = RawServer(config)
t = Tracker(config, r)
try:
#DEBUG
print "track: create_serversocket, port=", config['port']
#END
s = r.create_serversocket(config['port'], config['bind'])
handler = HTTPHandler(t.get, config['min_time_between_log_flushes'])
r.start_listening(s, handler)
except socket.error, e:
print ("Unable to open port %d. Use a different port?" %
config['port'])
return
r.listen_forever()
finally:
if t: t.save_dfile()
print _("# Shutting down: ") + isotime()
def size_format(s):
return str(Size(s))
def errorfunc( level, text ):
print "%s: %s" % (logging.getLevelName(level), text)
示例4: LaunchMany
# 需要导入模块: from BitTorrent.RawServer_twisted import RawServer [as 别名]
# 或者: from BitTorrent.RawServer_twisted.RawServer import listen_forever [as 别名]
#.........这里部分代码省略.........
All errors are logged using Python logging to 'configfile_key' logger.
@param config: Preferences object storing config.
@param display: output function for stats.
"""
# 4.4.x version of LaunchMany output exceptions to a displayer.
# This version only outputs stats to the displayer. We do not use
# the logger to output stats so that a caller-provided object
# can provide stats formatting as opposed to using the
# logger Formatter, which is specific to exceptions, warnings, and
# info messages.
self.logger = logging.getLogger(configfile_key)
try:
self.multitorrent = None
self.rawserver = None
self.config = config
self.configfile_key = configfile_key
self.display = display
self.torrent_dir = config['torrent_dir']
# Ex: torrent_cache = infohash -> (path,metainfo)
self.torrent_cache = {}
# maps path -> [(modification time, size), infohash]
self.file_cache = {}
# used as set containing paths of files that do not have separate
# entries in torrent_cache either because torrent_cache already
# contains the torrent or because the torrent file is corrupt.
self.blocked_files = {}
#self.torrent_list = []
#self.downloads = {}
self.hashcheck_queue = []
#self.hashcheck_store = {}
self.hashcheck_current = None
self.core_doneflag = DeferredEvent()
self.rawserver = RawServer(self.config)
try:
# set up shut-down procedure before we begin doing things that
# can throw exceptions.
def shutdown():
self.logger.critical(_("shutting down"))
for t in self.multitorrent.get_torrents():
self.logger.info(_('dropped "%s"') %
self.torrent_cache[t.infohash][0])
if self.multitorrent:
df = self.multitorrent.shutdown()
set_flag = lambda *a : self.rawserver.stop()
df.addCallbacks(set_flag, set_flag)
else:
self.rawserver.stop()
# It is safe to addCallback here, because there is only one thread,
# but even if the code were multi-threaded, core_doneflag has not
# been passed to anyone. There is no chance of a race condition
# between the DeferredEvent's callback and addCallback.
self.core_doneflag.addCallback(
lambda r: self.rawserver.external_add_task(0, shutdown))
self.rawserver.install_sigint_handler(self.core_doneflag)
data_dir = config['data_dir']
self.multitorrent = MultiTorrent(config, self.rawserver, data_dir,
resume_from_torrent_config=False)
self.rawserver.add_task(0, self.scan)
self.rawserver.add_task(0.5, self.periodic_check_hashcheck_queue)
self.rawserver.add_task(self.config['display_interval'],
self.periodic_stats)
try:
import signal
def handler(signum, frame):
self.rawserver.external_add_task(0, self.read_config)
signal.signal(signal.SIGHUP, handler)
except Exception, e:
self.logger.error(_("Could not set signal handler: ") +
str_exc(e))
self.rawserver.add_task(0,self.core_doneflag.set())
except UserFailure, e:
self.logger.error(str_exc(e))
self.rawserver.add_task(0,self.core_doneflag.set())
except:
data = StringIO()
print_exc(file = data)
self.logger.error(data.getvalue())
self.rawserver.add_task(0,self.core_doneflag.set())
# always make sure events get processed even if only for
# shutting down.
self.rawserver.listen_forever()
except:
示例5: _got_peer
# 需要导入模块: from BitTorrent.RawServer_twisted import RawServer [as 别名]
# 或者: from BitTorrent.RawServer_twisted.RawServer import listen_forever [as 别名]
def _got_peer(self, addr, infohash):
if self.got_peer:
self.got_peer(addr, infohash)
def stop(self):
self.port = None
self.got_peer = None
for service in self.services:
self.server.unregisterService(service)
del self.services[:]
if __name__ == '__main__':
import string
import threading
from BitTorrent.RawServer_twisted import RawServer
rawserver = RawServer()
def run_task_and_exit():
l = LocalDiscovery(rawserver, 6881,
lambda *a:sys.stdout.write("GOT: %s\n" % str(a)))
l.announce("63f27f5023d7e49840ce89fc1ff988336c514b64",
''.join(random.sample(string.letters, 5)))
rawserver.add_task(0, run_task_and_exit)
rawserver.listen_forever()
示例6: BTAppController
# 需要导入模块: from BitTorrent.RawServer_twisted import RawServer [as 别名]
# 或者: from BitTorrent.RawServer_twisted.RawServer import listen_forever [as 别名]
class BTAppController (NibClassBuilder.AutoBaseClass):
def init(self):
self = super(BTAppController, self).init()
self.prefs = Preferences.alloc().init()
self.prefwindow = None
self.generator = Generate.alloc().init()
self.ic =ICHelper.alloc().init()
# displayed torrent controllers
self.torrents = []
# waiting to die
self.dead_torrents = []
# ready to start
# (<open panel>, <insert row>, (<filename>|<stream>, <is_stream>)) -1 insert row means use last row
# stream = 0 if filename, 1 if bencoded torrent file
self.tqueue = []
self.retain()
self.inited = 0
self.launched = 0
self.in_choose = 0
self.last_qcheck = time()
self.sc = 0
self.defaults = NSUserDefaults.standardUserDefaults()
self.tup = bdecode(self.defaults.objectForKey_(ULBYTES))
self.tdown = bdecode(self.defaults.objectForKey_(DLBYTES))
self.config = common_options + rare_options
self.config = BTPreferences().initWithDict(dict([(name, value) for (name, value, doc) in self.config]))
self.config['data_dir'] = PREFDIR
self.config['bind'] = ''
self.config['bad_libc_workaround'] = True
self.config['filesystem_encoding'] = 'utf8'
#XXXX
#self.config['start_trackerless_client'] = False
self.legacyConfig()
self.reloadConfig()
self.pyi = None
self.doneflag = Event()
if not os.path.exists(PREFDIR):
os.mkdir(PREFDIR)
if not os.path.exists(RESDIR):
os.mkdir(RESDIR)
self.ticon = None
self.stalled = []
self.terminated = False
return self
def loadConsole_(self, sender):
if not self.pyi:
self.pyi = PyInterpreter.alloc().init()
NSBundle.loadNibNamed_owner_("PyInterpreter", self.pyi)
else:
self.pyi.textView.window().makeKeyAndOrderFront_(self)
def legacyConfig(self):
n = self.defaults.integerForKey_(QUEUESTOP)
if n > 1:
self.defaults.setObject_forKey_(0, QUEUESTOP)
def reloadConfig(self):
self.config['minport'] = self.defaults.integerForKey_(MINPORT)
self.config['maxport'] = self.defaults.integerForKey_(MINPORT)
self.config['max_upload_rate'] = self.defaults.integerForKey_(MAXULRATE)
self.config['max_allow_in'] = self.defaults.integerForKey_(MAXACCEPT)
self.config['max_initiate'] = self.defaults.integerForKey_(MAXINITIATE)
self.config['max_uploads'] = self.defaults.integerForKey_(MAXULS)
def listen_forever(self):
pool = NSAutoreleasePool.alloc().init()
# XXX
#self.profile = Profile("BT.prof");self.profile.start()
self.rawserver = RawServer(self.config)
self.mt = MultiTorrent(self.config, self.doneflag, self.rawserver, self.multi_errorfunc, self.config['data_dir'])
self.rawserver.ident = thread.get_ident()
self.mt.set_option("max_upload_rate", self.config['max_upload_rate'] * 1024)
self.rawserver.listen_forever(self.doneflag)
#self.profile.stop();self.profile.close()
def multi_errorfunc(self, level, text ):
if level == CRITICAL:
self.statusField.setStringValue_(NSLocalizedString("Critical Error: %s", "critical error") % text)
# bomb out
elif level == ERROR:
self.statusField.setStringValue_(NSLocalizedString("Error: %s", "normal error") % text)
#.........这里部分代码省略.........
示例7:
# 需要导入模块: from BitTorrent.RawServer_twisted import RawServer [as 别名]
# 或者: from BitTorrent.RawServer_twisted.RawServer import listen_forever [as 别名]
s.set_rate(rate)
for c in a:
s.add_data(c, c._use_length_)
t = task.LoopingCall(push)
t.start(freq)
rawserver.install_sigint_handler()
##############################################################
if profile:
try:
os.unlink(prof_file_name)
except:
pass
prof = hotshot.Profile(prof_file_name)
prof.start()
rawserver.listen_forever(doneflag)
prof.stop()
prof.close()
stats = hotshot.stats.load(prof_file_name)
stats.strip_dirs()
stats.sort_stats('time', 'calls')
print "NewRateLimiter Profile:"
stats.print_stats(20)
else:
##############################################################
rawserver.listen_forever(doneflag)