本文整理汇总了Python中multitask.add函数的典型用法代码示例。如果您正苦于以下问题:Python add函数的具体用法?Python add怎么用?Python add使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了add函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: start
def start(self, net=None, servers=None):
"""Start the p2p node as ordinary node. Create a network object if none."""
if self.net is None:
self.net = net or Network(Ks=crypto.generateRSA()[0], cert=None, port=self.port)
self.net.start()
# convert from serevrs ip:port list to Node list
if servers:
servers = [
Node(ip=ip, port=port, type=socket.SOCK_DGRAM, guid=H(ip + ":" + str(port))) for ip, port in servers
]
if _debug:
print "using servers=", servers
self.client = Client(self.net, server=self.server).start(servers)
if self.server:
if self.router is None:
self.router = dht.Router(self.net).start()
if self.storage is None:
self.storage = dht.Storage(self.net, self.router).start()
if not self.router.initialized:
self.router.initialized = True
if not self._gens:
for gen in [self.handler()]:
multitask.add(gen)
self._gens.append(gen)
return self
开发者ID:gavinljj,项目名称:p2p-sip,代码行数:27,代码来源:p2p.py
示例2: _sipreceiver
def _sipreceiver(self, stack, maxsize=16386):
'''Handle the messages or connections on the given SIP stack's socket, and pass it to the stack
so that stack can invoke appropriate callback on this object such as receivedRequest.'''
sock = stack.sock
def tcpreceiver(sock,
remote): # handle the messages on the given TCP connection.
while True:
data = yield multitask.recv(sock, maxsize)
if _debug: print '%r=>%r on type=%r\n%s' % (
remote, sock.getsockname(), sock.type, data)
if data: stack.received(data, remote)
while True:
if sock.type == socket.SOCK_DGRAM:
data, remote = yield multitask.recvfrom(sock, maxsize)
if _debug: print '%r=>%r on type=%r\n%s' % (
remote, sock.getsockname(), sock.type, data)
if data: stack.received(data, remote)
elif sock.type == socket.SOCK_STREAM:
conn, remote = yield multitask.accept(sock)
if conn:
self.conn[remote] = conn
multitask.add(tcpreceiver(conn, remote))
else:
raise ValueError, 'invalid socket type'
开发者ID:ikatson,项目名称:p2p-sip,代码行数:26,代码来源:agent.py
示例3: clienthandler
def clienthandler(self):
"""Receive requests from client and send to the router module, and viceversa."""
net = self.net
def requesthandler(msg):
p = msg.payload
response = None
if self.server: # only if a server
if p.name == "Put:Request":
result = yield dht.put(net, p.dest, p.value, p.nonce, p.expires, p.Ks, p.put)
response = Message(name="Put:Response", seq=p.seq, result=result)
elif p.name == "Get:Request":
result = yield dht.get(net, p.dest, p.maxvalues, p.Kp)
response = Message(name="Get:Response", seq=p.seq, guid=p.guid, vals=result)
if response:
yield self.net.send(
Message(name="Proxy:Response", src=net.node, payload=response), node=msg.src, timeout=5
)
def responsehandler(msg):
if not self.server: # only if a client
yield net.put(msg.payload, timeout=5)
while True:
msg = yield self.net.get(lambda x: x.name == "Proxy:Request" or x.name == "Proxy:Response")
if msg:
multitask.add(requesthandler(msg) if msg.name == "Proxy:Request" else responsehandler(msg))
开发者ID:gavinljj,项目名称:p2p-sip,代码行数:27,代码来源:p2p.py
示例4: __init__
def __init__(self, options):
''' Inits App with options and calls mainController()'''
logger.info("ntsga: init app")
self.options = options
self.status = []
self.user = None
multitask.add(self.mainController())
开发者ID:nitsuga1986,项目名称:sipot,代码行数:7,代码来源:sipot.py
示例5: clientlistener
def clientlistener(self, client):
'''Client listener (generator). It receives a command and invokes client handler, or receives a new stream and invokes streamlistener.'''
try:
while True:
msg, arg = (yield client.recv()) # receive new message from client
if not msg: # if the client disconnected,
if _debug: print 'connection closed from client'
break # come out of listening loop.
if msg == 'command': # handle a new command
multitask.add(self.clienthandler(client, arg))
elif msg == 'stream': # a new stream is created, handle the stream.
arg.client = client
multitask.add(self.streamlistener(arg))
except StopIteration: raise
except:
if _debug: print 'clientlistener exception', (sys and sys.exc_info() or None)
traceback.print_exc()
# client is disconnected, clear our state for application instance.
if _debug: print 'cleaning up client', client.path
inst = None
if client.path in self.clients:
inst = self.clients[client.path][0]
self.clients[client.path].remove(client)
for stream in client.streams.values(): # for all streams of this client
self.closehandler(stream)
client.streams.clear() # and clear the collection of streams
if client.path in self.clients and len(self.clients[client.path]) == 1: # no more clients left, delete the instance.
if _debug: print 'removing the application instance'
inst = self.clients[client.path][0]
inst._clients = None
del self.clients[client.path]
if inst is not None: inst.onDisconnect(client)
开发者ID:physicalfix,项目名称:physicalfix,代码行数:33,代码来源:rtmp.py
示例6: add_setCrashDetectGen
def add_setCrashDetectGen(self):
self.app.status.append('Crash detection Initiated')
self.state = self.SETTING_CRASH_DETECT
if not self._setCrashGen:
self._setCrashGen = self._setCrashDetect()
multitask.add(self._setCrashGen)
return self
开发者ID:nitsuga1986,项目名称:sipot,代码行数:7,代码来源:module_fuzzer.py
示例7: send
def send(self, data, addr, stack):
'''Send data to the remote addr.'''
def _send(self, data, addr): # generator version
try:
logger.debug('sending[%d] to %s\n%s'%(len(data), addr, data))
if self.sock:
if self.sock.type == socket.SOCK_STREAM:
try:
remote = self.sock.getpeername()
if remote != addr:
logger.debug('connected to wrong addr', remote, 'but sending to', addr)
except socket.error: # not connected, try connecting
try:
self.sock.connect(addr)
except socket.error:
logger.debug('failed to connect to', addr)
try:
yield self.sock.send(data)
except socket.error:
logger.debug('socket error in send')
elif self.sock.type == socket.SOCK_DGRAM:
try:
yield self.sock.sendto(data, addr)
except socket.error:
logger.debug('socket error in sendto' )
else:
logger.debug('invalid socket type', self.sock.type)
except AttributeError: pass
multitask.add(_send(self, data, addr))
开发者ID:nitsuga1986,项目名称:sipot,代码行数:29,代码来源:sipot.py
示例8: start
def start(self, delay=None):
import multitask
if self.running: self.stop() # stop previous one first.
if delay is not None: self.delay = delay # set the new delay
self.running = True
self.gen = self.run()
multitask.add(self.gen)
开发者ID:przypieczony,项目名称:thesis,代码行数:7,代码来源:kutil.py
示例9: allocateRequest
def allocateRequest(sock, m, remote): # serve the allocate request of TURN
fivetuple = (sock.type, getlocaladdr(sock), remote)
lifetime = timeout
if Attribute.LIFETIME in m:
lt = struct.unpack('!L', m[Attribute.LIFETIME].value)
if lt < lifetime: lifetime = lt
if fivetuple in binding: # already found
newsock = binding[fivetuple]
if lifetime == 0: # terminate the binding
del binding[fivetuple]
del binding[newsock]
else:
if lifetime > 0: # allocate, otherwise it is already missing.
newsock = socket.socket(sock.family, sock.type)
newsock.bind(('0.0.0.0', 0)) # bind to any
binding[newsock] = fivetuple
binding[fivetuple] = newsock
res = Message()
res.method, res.type, res.tid = m.method, Message.RESPONSE, m.tid
mapped = Attribute(Attribute.MAPPED_ADDRESS) # mapped-address attribute
mapped.address = (newsock.family, (external, newsock and newsock.getsockname()[1] or 0))
res.attrs.append(mapped)
res.attrs.append(Attribute(Attribute.LIFETIME, struct.pack('!L', lifetime)))
if lifetime == 0 and newsock: # close any previous listening function
newsock.close() # this should trigger close of functions
else:
if sock.type == socket.SOCK_STREAM:
multitask.add(relayaccepter(newsock, fivetuple))
else:
multitask.add(relayreceiver(newsock, fivetuple))
yield respond(sock, str(res), remote)
开发者ID:ATOM49,项目名称:django-voip,代码行数:34,代码来源:rfc3489bis.py
示例10: test1
def test1(publishers, players):
duration = 30
for i in xrange(publishers):
url, stream = 'rtmp://localhost/live%d'%(i,), 'live'
multitask.add(rtmpclient.connect(url, publishFile='file1.flv', publishStream=stream, playStream=None, duration=duration, params=[]))
for j in xrange(players):
multitask.add(rtmpclient.connect(url, playStream=stream, duration=duration, params=[]))
开发者ID:LouisPlisso,项目名称:visemo,代码行数:7,代码来源:test_load.py
示例11: onConnect
def onConnect(self, client, *args):
result = rtmp.App.onConnect(self, client, *args)
self.clientId += 1
client.clientId = self.clientId
def invokeAdded(
self, client
): # invoke the added and published callbacks on this client, and added on other clients.
for other in filter(lambda x: x != client, self.clients):
client.call("added", str(other.clientId))
other.call("added", str(client.clientId))
for stream in filter(lambda x: x.client != client, self.publishers.values()):
client.call("published", str(stream.client.clientId), stream.name)
yield
multitask.add(
invokeAdded(self, client)
) # need to invoke later so that connection is established before callback
# if _debug:
# def printBW(client, interval=5):
# while True:
# yield multitask.sleep(interval)
# print 'client bandwidth up=', int(client.stream.bytesRead*8/interval*0.001),'down=', int(client.stream.bytesWritten*8/interval*0.001)
# client.stream.bytesRead = client.stream.bytesWritten = 0
# self._bwthread = printBW(client)
# multitask.add(self._bwthread)
return result
开发者ID:BillTheBest,项目名称:videocity,代码行数:27,代码来源:videocity.py
示例12: receivedRequest
def receivedRequest(self, ua, request, stack):
'''Callback when received an incoming request.'''
def _receivedRequest(self, ua, request): # a generator version
logger.debug('receivedRequest method=', request.method, 'ua=', ua, ' for ua', (ua.queue is not None and 'with queue' or 'without queue') )
if hasattr(ua, 'queue') and ua.queue is not None:
yield ua.queue.put(request)
elif request.method == 'INVITE': # a new invitation
if self._queue is not None:
if not request['Conf-ID']: # regular call invitation
yield self._queue.put(('connect', (str(request.From.value), ua)))
else: # conference invitation
if request['Invited-By']:
yield self._queue.put(('confconnect', (str(request.From.value), ua)))
else:
yield self._queue.put(('confinvite', (str(request.From.value), ua)))
else:
ua.sendResponse(405, 'Method not allowed')
elif request.method == 'SUBSCRIBE': # a new watch request
if self._queue:
yield self._queue.put(('watch', (str(request.From.value), ua)))
else:
ua.sendResponse(405, 'Method not allowed')
elif request.method == 'MESSAGE': # a paging-mode instant message
if request.body and self._queue:
ua.sendResponse(200, 'OK') # blindly accept the message
yield self._queue.put(('send', (str(request.From.value), request.body)))
else:
ua.sendResponse(405, 'Method not allowed')
elif request.method == 'CANCEL':
# TODO: non-dialog CANCEL comes here. need to fix rfc3261_IPv6 so that it goes to cancelled() callback.
if ua.request.method == 'INVITE': # only INVITE is allowed to be cancelled.
yield self._queue.put(('close', (str(request.From.value), ua)))
else:
ua.sendResponse(405, 'Method not allowed')
multitask.add(_receivedRequest(self, ua, request))
开发者ID:nitsuga1986,项目名称:sipot,代码行数:35,代码来源:sipot.py
示例13: handshake
def handshake(self): # Implement the client side of the handshake. Must be invoked by caller after TCP connection completes.
yield self.stream.write('\x03' + '\x00'*(Protocol.PING_SIZE)) # send first handshake
data = (yield self.stream.read(Protocol.PING_SIZE + 1))
yield self.stream.write(data[1:]) # send second handshake
data = (yield self.stream.read(Protocol.PING_SIZE))
multitask.add(self.parse()); multitask.add(self.write()) # launch the reader and writer tasks
raise StopIteration, self
开发者ID:ATOM49,项目名称:django-voip,代码行数:7,代码来源:rtmpclient.py
示例14: cancelled
def cancelled(self, ua, request, stack):
'''Callback when given original request has been cancelled by remote.'''
def _cancelled(self, ua, request): # a generator version
if hasattr(ua, 'queue') and ua.queue is not None:
yield ua.queue.put(request)
elif self._queue is not None and ua.request.method == 'INVITE': # only INVITE is allowed to be cancelled.
yield self._queue.put(('close', (str(request.From.value), ua)))
multitask.add(_cancelled(self, ua, request))
开发者ID:nitsuga1986,项目名称:sipot,代码行数:8,代码来源:sipot.py
示例15: open
def open(self, url):
if _debug: print 'FLVReader.open', url
self.url, u = url, urlparse.urlparse(url, 'file')
self.fp = FLV().open(u.path)
if self.fp:
self._gen = self.fp.reader(self); multitask.add(self._gen)
raise StopIteration, self
else: raise StopIteration, None
开发者ID:ATOM49,项目名称:django-voip,代码行数:8,代码来源:rtmpclient.py
示例16: _testServer
def _testServer():
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, 0)
sock.bind(('0.0.0.0', 0)) # should use any port for testing
multitask.add(server(sock))
sockaddr = getlocaladdr(sock)
multitask.add(_testDiscoverBehavior([sockaddr, defaultServers[0]]))
yield multitask.sleep(5)
sock.close()
开发者ID:ATOM49,项目名称:django-voip,代码行数:8,代码来源:rfc3489bis.py
示例17: p2preceiver
def p2preceiver(self, p2p):
'''Receive packets or connections from p2p socket server.'''
def p2phandler(self, sock): # Handle the messages on the given P2P connection.
while True:
data = yield sock.recv()
while True:
sock = yield p2p.accept()
if hasattr(self, 'identity') and self.identity: multitask.add(p2phandler(sock))
开发者ID:Atom-machinerule,项目名称:Atoms_custom_webi,代码行数:8,代码来源:p2psip.py
示例18: _testAlgorithm
def _testAlgorithm():
def testInternal():
#global _debug
#_debug = dht._debug = True
nodes = [ServerSocket(True).start()]
for x in xrange(10):
nodes.append(ServerSocket().start())
yield
multitask.add(testInternal())
开发者ID:ATOM49,项目名称:django-voip,代码行数:9,代码来源:p2p.py
示例19: _testClient
def _testClient():
def internalTest():
n1 = Network(crypto.PrivateKey(), '').start()
n2 = Network(crypto.PrivateKey(), '').start()
c1 = Client(n1, server=True).start()
c2 = Client(n2).start()
msg = yield n2.get(lambda x: x.name=='Discover:Indication', timeout=8)
assert msg is not None and msg.neighbors[0] == n1.node
multitask.add(internalTest()) # need to use a generator for test
开发者ID:ATOM49,项目名称:django-voip,代码行数:9,代码来源:p2p.py
示例20: onDisconnect
def onDisconnect(self, client):
rtmp.App.onDisconnect(self, client)
if hasattr(self, '_bwthread'): self._bwthread.close()
def invokeRemoved(self, client): # invoke the removed callbacks on other clients
for other in filter(lambda x: x != client, self.clients):
yield other.call('removed', str(client.clientId))
yield
if filter(lambda x: x != client, self.clients): multitask.add(invokeRemoved(self, client))
else: webscript.delete(path=client.path.partition('/')[2])
开发者ID:BillTheBest,项目名称:videocity,代码行数:9,代码来源:server.py
注:本文中的multitask.add函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论