本文整理汇总了Python中multiprocessing.connection.Listener.accept方法的典型用法代码示例。如果您正苦于以下问题:Python Listener.accept方法的具体用法?Python Listener.accept怎么用?Python Listener.accept使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类multiprocessing.connection.Listener
的用法示例。
在下文中一共展示了Listener.accept方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: CountApiServer
# 需要导入模块: from multiprocessing.connection import Listener [as 别名]
# 或者: from multiprocessing.connection.Listener import accept [as 别名]
class CountApiServer(threading.Thread):
def __init__(self, port, parent):
super(CountApiServer, self).__init__()
self.parent = parent
self.__listener = Listener(('127.0.0.1', port))
def run(self):
conn = self.__listener.accept()
while 1:
if conn.closed:
conn = self.__listener.accept()
try:
msg = conn.recv()
except EOFError:
conn.close()
continue
else:
if msg == 'quit':
conn.close()
break
conn.send(self.parent.key_count)
self.__listener.close()
self.parent.stop()
示例2: main
# 需要导入模块: from multiprocessing.connection import Listener [as 别名]
# 或者: from multiprocessing.connection.Listener import accept [as 别名]
def main():
_setproctitle('structurarium.graph')
parser = argparse.ArgumentParser(description='Run Structurarium graph server')
parser.add_argument('--version', '-v', action='version', version=__version__)
parser.add_argument('host')
parser.add_argument('port', type=int)
parser.add_argument('path')
parser.add_argument('--authkey', '-k', action='store')
parser.add_argument(
'--worker',
'-w',
action='store',
type=int,
help='default is set to the number of CPU'
)
args = parser.parse_args()
listener = Listener((args.host, args.port), family='AF_INET')
database = Graph(args.path, authkey=args.authkey)
pool = Pool(processes=args.worker)
print 'Running on %s:%s' % (args.host, args.port)
while True:
connection = listener.accept()
connection = reduce_connection(connection)
# pool.apply_async(connect, [database, connection])
connect(database, connection)
示例3: worker
# 需要导入模块: from multiprocessing.connection import Listener [as 别名]
# 或者: from multiprocessing.connection.Listener import accept [as 别名]
def worker(address, port, password):
listener = Listener(address, authkey=password)
conn = listener.accept()
print 'connection accepted from', listener.last_accepted
conn.send_bytes('hello')
conn.close()
listener.close()
示例4: main
# 需要导入模块: from multiprocessing.connection import Listener [as 别名]
# 或者: from multiprocessing.connection.Listener import accept [as 别名]
def main():
setproctitle('graph4py.rpc')
parser = argparse.ArgumentParser(description='Run Graph4Py graph server')
parser.add_argument(
'--version',
'-v',
action='version',
version=__version__
)
parser.add_argument('host')
parser.add_argument('port', type=int)
parser.add_argument('backend')
parser.add_argument('path')
parser.add_argument('--authkey', '-k', action='store')
parser.add_argument('--graph', '-g', action='store')
args = parser.parse_args()
graph_class = import_object(args.graph) if args.graph else None
database = Graph4Py(args.backend, args.path, args.authkey, graph_class)
def signal_handler(s, frame):
database.close()
sys.exit(0)
signal.signal(signal.SIGINT, signal_handler)
listener = Listener((args.host, args.port), family='AF_INET')
print 'Running on %s:%s with %s' % (args.host, args.port, database.graph)
while True:
connection = listener.accept()
database.process(connection)
示例5: rpc_server
# 需要导入模块: from multiprocessing.connection import Listener [as 别名]
# 或者: from multiprocessing.connection.Listener import accept [as 别名]
def rpc_server(handler, address, authkey):
sock = Listener(address, authkey=authkey)
while True:
client = sock.accept()
t = Thread(target=handler.handle_connection, args=(client,))
t.daemon = True
t.start()
示例6: PctrlListener
# 需要导入模块: from multiprocessing.connection import Listener [as 别名]
# 或者: from multiprocessing.connection.Listener import accept [as 别名]
class PctrlListener(object):
def __init__(self):
logger.info("Initializing the BGP PctrlListener")
self.listener = Listener(config.ah_socket, authkey=None, backlog=128)
logger.debug('SOCKSTAT ' + str(self.listener))
self.run = True
def start(self):
logger.info("Starting the BGP PctrlListener")
while self.run:
conn = self.listener.accept()
logger.debug('SOCKSTAT ' + str(self.listener.last_accepted))
pc = PctrlClient(conn, self.listener.last_accepted)
t = Thread(target=pc.start)
with clientPoolLock:
logger.debug('Trace: PctrlListener.start: clientActivePool before: %s', clientActivePool)
logger.debug('Trace: PctrlListener.start: clientDeadPool before: %s', clientDeadPool)
clientActivePool[pc] = t
# while here, join dead threads.
while clientDeadPool:
clientDeadPool.pop().join()
logger.debug('Trace: PctrlListener.start: clientActivePool after: %s', clientActivePool)
logger.debug('Trace: PctrlListener.start: clientDeadPool after: %s', clientDeadPool)
t.start()
def stop(self):
logger.info("Stopping PctrlListener.")
self.run = False
示例7: PolicyHandler
# 需要导入模块: from multiprocessing.connection import Listener [as 别名]
# 或者: from multiprocessing.connection.Listener import accept [as 别名]
class PolicyHandler():
def __init__(self,event_queue,ready_queue,sdx):
self.event_queue = event_queue
self.ready_queue = ready_queue
self.sdx = sdx
self.listener = Listener(('localhost', 6999), authkey=None)
def start(self):
while True:
self.conn = self.listener.accept()
print 'Policy Handler: Connection accepted from', self.listener.last_accepted
tmp = self.conn.recv()
data = json.loads(tmp)
print data, type(data)
print data.keys()
print self.sdx.policy_status.keys()
for pname in data:
self.sdx.policy_status[pname] = int(data[pname])
print data, self.sdx.policy_status
self.conn.send('Policy Handler: Hello World')
self.conn.close()
self.event_queue.put('Policy Handler: Policy Status changed for ')
示例8: _serve
# 需要导入模块: from multiprocessing.connection import Listener [as 别名]
# 或者: from multiprocessing.connection.Listener import accept [as 别名]
def _serve(self, port, path):
data = []
# print 'Server', os.getpid()
address = ('localhost', port)
listener = Listener(address)
loop = True
while loop:
conn = listener.accept()
command, payload = conn.recv()
response_payload = None
if command == 'OPEN':
#print command, payload
path = payload
elif command == 'WRITE':
#print command, payload
data.append(payload)
elif command == 'FETCH':
#print command, payload
response_payload = data
elif command == 'FLUSH':
#print command
json.dump(data, open(path, 'w'))
elif command == 'CLOSE':
#print command
#json.dump(data, open(path, 'w'))
loop = False
conn.send(('OK', response_payload))
conn.close()
listener.close()
示例9: loop
# 需要导入模块: from multiprocessing.connection import Listener [as 别名]
# 或者: from multiprocessing.connection.Listener import accept [as 别名]
def loop(self):
listener = Listener(self.address, backlog=5, authkey=self.authkey)
logging.warn('DB server started with %s, listening on %s:%d...',
sys.executable, *self.address)
self.thread.start()
cmd = None
try:
while cmd != 'stop':
try:
conn = listener.accept()
except KeyboardInterrupt:
break
except:
# unauthenticated connection, for instance by a port
# scanner such as the one in manage.py
continue
cmd_ = conn.recv() # a tuple (name, arg1, ... argN)
cmd, args = cmd_[0], cmd_[1:]
if cmd.startswith('@'): # slow command, run in process
cmd = cmd[1:] # strip @
proc = Process(
target=run_command, name=cmd, args=(cmd, args, conn))
proc.start()
logging.warn('Started %s%s in process %d',
cmd, args, proc.pid)
else:
queue.put((conn, cmd, args))
finally:
listener.close()
self.thread.join()
示例10: objectLogger
# 需要导入模块: from multiprocessing.connection import Listener [as 别名]
# 或者: from multiprocessing.connection.Listener import accept [as 别名]
def objectLogger(params):
""" Send data (dict, str, ...) into a storage """
mode = params['mode']
maxlen = params['maxlen']
file_format = params['format']
home_dir = params['storage_dir']
server = Listener((params['ip'], int(params['port'])))
storage = PersistentDeque(
home_dir=home_dir,
maxlen=maxlen,
file_format=file_format,
mode=mode,
)
while True:
conn = server.accept()
while True:
try:
data = conn.recv()
except EOFError:
break
if data:
storage.append(data)
else:
storage.sync(id_generator())
storage = PersistentDeque(
home_dir=home_dir,
maxlen=maxlen,
file_format=file_format,
mode=mode,
)
conn.close()
示例11: __init__
# 需要导入模块: from multiprocessing.connection import Listener [as 别名]
# 或者: from multiprocessing.connection.Listener import accept [as 别名]
class Server:
def __init__(self, in_file):
self.pids = set([])
self.pids.add(os.getppid())
self.address = ('localhost', 6000)
self.listener = Listener(self.address, authkey='s'.encode(encoding='UTF-8'))
self.shell_file = os.environ['HOME'] + '/.pyplayer'
self.player = Player(in_file)
self.interface = Interface(self.player)
def run(self):
cont = True
watcher = Watcher(self.interface, self.shell_file, self.pids)
watcher.start()
while cont:
conn = self.listener.accept()
print('Connection from', self.listener.last_accepted)
msg = conn.recv()
print(msg)
self.pids.add(msg['pid'])
cont, info = self.interface.process_msg(msg['args'])
watcher.notify_changes()
conn.send(info)
conn.close()
watcher.stop()
watcher.join()
示例12: rpc
# 需要导入模块: from multiprocessing.connection import Listener [as 别名]
# 或者: from multiprocessing.connection.Listener import accept [as 别名]
def rpc(self, dest, method, args=None, kwargs=None):
""" Make an RPC call to the named subscriber, expecting a
response. This opens a
:class:`multiprocessing.connection.Listener` and passes the
Listener address to the child as part of the RPC call, so that
the child can connect to the Listener to submit its results.
Listeners are reused when possible to minimize overhead.
"""
try:
listener = self._available_listeners.get_nowait()
self.logger.debug("Reusing existing RPC listener at %s" %
listener.address)
except Empty:
listener = Listener()
self.logger.debug("Created new RPC listener at %s" %
listener.address)
self._blocking_listeners.append(listener)
try:
self._queues[dest].put((listener.address,
(method, args or [], kwargs or dict())))
conn = listener.accept()
self._blocking_listeners.remove(listener)
try:
while not self._terminate.is_set():
if conn.poll(self.poll_wait):
return conn.recv()
finally:
conn.close()
finally:
self._available_listeners.put(listener)
示例13: SimpleSynergeticServer
# 需要导入模块: from multiprocessing.connection import Listener [as 别名]
# 或者: from multiprocessing.connection.Listener import accept [as 别名]
class SimpleSynergeticServer(Process):
def __init__(self, authen_key):
Process.__init__(self)
self.__task_queue = JoinableQueue(1)
self.__return_queue = Queue(1)
self.serv = Listener(('', 40000), authkey=authen_key)
def run(self):
print 'Server Works'
copy_reg.pickle(types.MethodType, _reduce_method)
#Start the synergeticProcess in Deamon Mode
worker_p = SynergeticProcess(self.__task_queue, self.__return_queue)
worker_p.deamon = True
worker_p.start()
while True:
print 'wait for Client'
pool_conn = self.serv.accept()
print 'connection Client Accepted'
while True:
print 'in LOOP Simple Server'
#There is no need for task_id in this version
try:
print 'Try to recv MSG'
unpickled_msg = pool_conn.recv()
print 'MSG Reseved'
except Exception as e: # EOFError:
print 'Fail To Receive MSG:', e
break
if unpickled_msg[0] == 'MODULES':
self.import_mods( unpickled_msg[1] )
ret = 'MODULES-READY'
else:
self.__task_queue.put(unpickled_msg)
ret = self.__return_queue.get()
try:
print 'SEND RESPONCE'
try:
pool_conn.send( ret )
except EOFError:
print 'SENT TO POOL FAILD'
print 'RESPONCE SENT ', ret
except EOFError:
break
pool_conn.close()
def import_mods(self, mods_d):
for mod_name, mod_bytecode in mods_d.items():
try:
fobj = open(mod_name + ".pyc", 'wb')
except Exception as e:
print("Synergeticprocessing.SimpleServer --> Module file error: %s" % e)
else:
fobj.write( mod_bytecode )
finally:
fobj.close()
for mod in mods_d:
print 'blocking'
__import__( mod )
print 'imported ', mod
示例14: echo_server
# 需要导入模块: from multiprocessing.connection import Listener [as 别名]
# 或者: from multiprocessing.connection.Listener import accept [as 别名]
def echo_server(address, authkey):
serv = Listener(address, authkey=authkey)
while True:
try:
client = serv.accept()
echo_client(client)
except Exception:
traceback.print_exc()
示例15: start
# 需要导入模块: from multiprocessing.connection import Listener [as 别名]
# 或者: from multiprocessing.connection.Listener import accept [as 别名]
def start(self):
address = ('localhost', 6000)
listener = Listener(address)
conn = listener.accept()
while True:
msg = conn.recv()
self.log_id += 1
self.log_file.add_row(LogEntry([self.node_id, self.log_id, msg]))