當前位置: 首頁>>代碼示例>>Python>>正文


Python asyncio.start_unix_server方法代碼示例

本文整理匯總了Python中asyncio.start_unix_server方法的典型用法代碼示例。如果您正苦於以下問題:Python asyncio.start_unix_server方法的具體用法?Python asyncio.start_unix_server怎麽用?Python asyncio.start_unix_server使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在asyncio的用法示例。


在下文中一共展示了asyncio.start_unix_server方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: _start_server

# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import start_unix_server [as 別名]
def _start_server(self, ipc_path: Path) -> None:
        """
        Start serving this :class:`~lahja.endpoint.asyncio.AsyncioEndpoint` so that it
        can receive events. Await until the
        :class:`~lahja.endpoint.asyncio.AsyncioEndpoint` is ready.
        """
        if not self.is_running:
            raise RuntimeError(f"Endpoint {self.name} must be running to start server")
        elif self.is_serving:
            raise RuntimeError(f"Endpoint {self.name} is already serving")

        self._ipc_path = ipc_path

        self._serving = True

        self._server = await asyncio.start_unix_server(
            self._accept_conn, path=str(self.ipc_path)
        )
        self.logger.debug("Endpoint[%s]: server started", self.name) 
開發者ID:ethereum,項目名稱:lahja,代碼行數:21,代碼來源:endpoint.py

示例2: start_interactive_server

# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import start_unix_server [as 別名]
def start_interactive_server(
    factory=console.AsynchronousConsole,
    host=None,
    port=None,
    path=None,
    banner=None,
    *,
    loop=None
):
    if (port is None) == (path is None):
        raise ValueError("Either a TCP port or a UDS path should be provided")
    if port is not None:
        # Override asyncio behavior (i.e serve on all interfaces by default)
        host = host or "localhost"
        start_server = partial(asyncio.start_server, host=host, port=port)
    else:
        start_server = partial(asyncio.start_unix_server, path=path)

    client_connected = partial(handle_connect, factory=factory, banner=banner)
    server = await start_server(client_connected, loop=loop)
    return server 
開發者ID:vxgmichel,項目名稱:aioconsole,代碼行數:23,代碼來源:server.py

示例3: create_servers

# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import start_unix_server [as 別名]
def create_servers(loop):
    servers = []

    reuse_port = hasattr(socket, "SO_REUSEPORT")
    has_unix = hasattr(socket, "AF_UNIX")

    if config.LISTEN_ADDR_IPV4:
        task = asyncio.start_server(handle_client_wrapper, config.LISTEN_ADDR_IPV4, config.PORT,
                                    limit=get_to_tg_bufsize(), reuse_port=reuse_port)
        servers.append(loop.run_until_complete(task))

    if config.LISTEN_ADDR_IPV6 and socket.has_ipv6:
        task = asyncio.start_server(handle_client_wrapper, config.LISTEN_ADDR_IPV6, config.PORT,
                                    limit=get_to_tg_bufsize(), reuse_port=reuse_port)
        servers.append(loop.run_until_complete(task))

    if config.LISTEN_UNIX_SOCK and has_unix:
        remove_unix_socket(config.LISTEN_UNIX_SOCK)
        task = asyncio.start_unix_server(handle_client_wrapper, config.LISTEN_UNIX_SOCK,
                                         limit=get_to_tg_bufsize())
        servers.append(loop.run_until_complete(task))
        os.chmod(config.LISTEN_UNIX_SOCK, 0o666)

    if config.METRICS_PORT is not None:
        if config.METRICS_LISTEN_ADDR_IPV4:
            task = asyncio.start_server(handle_metrics, config.METRICS_LISTEN_ADDR_IPV4,
                                        config.METRICS_PORT)
            servers.append(loop.run_until_complete(task))
        if config.METRICS_LISTEN_ADDR_IPV6 and socket.has_ipv6:
            task = asyncio.start_server(handle_metrics, config.METRICS_LISTEN_ADDR_IPV6,
                                        config.METRICS_PORT)
            servers.append(loop.run_until_complete(task))

    return servers 
開發者ID:alexbers,項目名稱:mtprotoproxy,代碼行數:36,代碼來源:mtprotoproxy.py

示例4: start_server

# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import start_unix_server [as 別名]
def start_server(handle, hostinfo):
    if is_path(hostinfo):
        try:
            os.remove(hostinfo)
        except FileNotFoundError:
            pass
        server = await asyncio.start_unix_server(handle, path=hostinfo)
        os.chmod(hostinfo, 0o666)
        return server
    host = Host(hostinfo)
    return await asyncio.start_server(handle, host=host.hostname, port=host.port) 
開發者ID:gera2ld,項目名稱:async_dns,代碼行數:13,代碼來源:serve.py

示例5: start_manhole

# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import start_unix_server [as 別名]
def start_manhole(path: str, banner: str = "", namespace: Optional[Dict[str, Any]] = None,
                        loop: asyncio.AbstractEventLoop = None, whitelist: Set[int] = None,
                        ) -> Tuple[asyncio.AbstractServer, Callable[[], None]]:
    """
    Starts a manhole server on a given UNIX address.

    Args:
        path: The path to create the UNIX socket at.
        banner: The banner to show when clients connect.
        namespace: The globals to provide to connected clients.
        loop: The asyncio event loop to use.
        whitelist: List of user IDs to allow connecting.
    """
    if not SO_PEERCRED:
        raise ValueError("SO_PEERCRED is not supported on this platform")
    loop = loop or asyncio.get_event_loop()
    factory = InterpreterFactory(namespace=namespace, banner=banner,
                                 interpreter_class=AsyncInterpreter, loop=loop,
                                 whitelist=whitelist)
    server = await asyncio.start_unix_server(factory, path=path, loop=loop)
    os.chmod(path, 0o666)

    def stop():
        for client in factory.clients:
            client.close()
        server.close()

    return server, stop 
開發者ID:tulir,項目名稱:mautrix-python,代碼行數:30,代碼來源:manhole.py

示例6: server

# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import start_unix_server [as 別名]
def server(hub):
    '''
    Start the unix socket server to receive commands
    '''
    await asyncio.start_unix_server(
            hub.proc.worker.work,
            path=hub.proc.SOCK_PATH) 
開發者ID:saltstack,項目名稱:pop,代碼行數:9,代碼來源:worker.py

示例7: pool

# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import start_unix_server [as 別名]
def pool(hub, num, name='Workers', callback=None, sock_dir=None):
    '''
    Create a new local pool of process based workers

    :param num: The number of processes to add to this pool
    :param ref: The location on the hub to create the Workers dict used to
        store the worker pool, defaults to `hub.pop.proc.Workers`
    :param callback: The pop ref to call when the process communicates
        back
    '''
    ret_ref = os.urandom(3).hex() + '.sock'
    ret_sock_path = os.path.join(sock_dir, ret_ref)
    if not hub.proc.Tracker:
        hub.proc.init.mk_tracker()
    workers = {}
    if callback:
        await asyncio.start_unix_server(
                hub.proc.init.ret_work(callback),
                path=ret_sock_path)
    for ind in range(num):
        hub.proc.init.mk_proc(ind, workers, ret_ref, sock_dir)
    w_iter = itertools.cycle(workers)
    hub.proc.Workers[name] = workers
    hub.proc.WorkersIter[name] = w_iter
    hub.proc.WorkersTrack[name] = {
        'subs': [],
        'ret_ref': ret_ref,
        'sock_dir': sock_dir}
    up = set()
    while True:
        for ind in workers:
            if os.path.exists(workers[ind]['path']):
                up.add(ind)
        if len(up) == num:
            break
        await asyncio.sleep(0.01)
    # TODO: This seems to be spawning extra procs, this should be fixed
    #asyncio.ensure_future(hub.proc.init.maintain(name)) 
開發者ID:saltstack,項目名稱:pop,代碼行數:40,代碼來源:init.py

示例8: start

# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import start_unix_server [as 別名]
def start(self):
        def _spawn(reader, writer):
            def done_cb(task, fut):
                self._children.discard(task)
            task = self._loop.create_task(self.handler(reader, writer))
            task.add_done_callback(partial(done_cb, task))
            self._children.add(task)
            self._logger.debug("len(self._children) = %d", len(self._children))

        if self._unix:
            self._server = await asyncio.start_unix_server(_spawn, path=self._path)
            if self._sockmode is not None:
                os.chmod(self._path, self._sockmode)
        else:
            if self._reuse_port: # pragma: no cover
                if sys.platform in ('win32', 'cygwin'):
                    opts = {
                        'host': self._host,
                        'port': self._port,
                        'reuse_address': True,
                    }
                elif os.name == 'posix':
                    if sys.platform.startswith('freebsd'):
                        sockopts = [
                            (socket.SOL_SOCKET, socket.SO_REUSEADDR, 1),
                            (socket.SOL_SOCKET, 0x10000, 1),  # SO_REUSEPORT_LB
                        ]
                        sock = await create_custom_socket(self._host, self._port,
                                                          options=sockopts)
                        opts = {
                            'sock': sock,
                        }
                    else:
                        opts = {
                            'host': self._host,
                            'port': self._port,
                            'reuse_address': True,
                            'reuse_port': True,
                        }
            self._server = await asyncio.start_server(_spawn, **opts) 
開發者ID:Snawoot,項目名稱:postfix-mta-sts-resolver,代碼行數:42,代碼來源:responder.py

示例9: client_run

# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import start_unix_server [as 別名]
def client_run(self, args):
        async def handler(reader, writer):
            if self.uri.auth:
                try:
                    assert self.uri.auth == (await reader.read_n(len(self.uri.auth)))
                except Exception:
                    return
            await self.conn.put((reader, writer))
        if self.uri.unix:
            return asyncio.start_unix_server(handler, path=self.uri.bind)
        else:
            return asyncio.start_server(handler, host=self.uri.host_name, port=self.uri.port, reuse_port=args.get('ruport')) 
開發者ID:qwj,項目名稱:python-proxy,代碼行數:14,代碼來源:server.py

示例10: start_server

# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import start_unix_server [as 別名]
def start_server(self, args):
        handler = functools.partial(reuse_stream_handler if self.reuse else stream_handler, **vars(self), **args)
        if self.backward:
            return self.backward.start_server(handler)
        elif self.unix:
            return asyncio.start_unix_server(handler, path=self.bind)
        else:
            return asyncio.start_server(handler, host=self.host_name, port=self.port, reuse_port=args.get('ruport')) 
開發者ID:qwj,項目名稱:python-proxy,代碼行數:10,代碼來源:server.py

示例11: run_sum_server

# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import start_unix_server [as 別名]
def run_sum_server():
    def sum(x, y):
        return x + y

    aiorpc.register('sum', sum)
    loop = uvloop.new_event_loop()
    asyncio.set_event_loop(loop)
    coro = asyncio.start_unix_server(aiorpc.serve, './benchmark.socket', loop=loop)
    loop.run_until_complete(coro)
    loop.run_forever() 
開發者ID:choleraehyq,項目名稱:aiorpc,代碼行數:12,代碼來源:benchmark_aiorpc_unix.py

示例12: set_up_unix_server

# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import start_unix_server [as 別名]
def set_up_unix_server():
    global loop, unix_server
    if not loop:
        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)
    coro = asyncio.start_unix_server(serve, PATH)
    unix_server = loop.run_until_complete(coro) 
開發者ID:choleraehyq,項目名稱:aiorpc,代碼行數:9,代碼來源:test_rpc.py

示例13: __init__

# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import start_unix_server [as 別名]
def __init__(self,
                 model_config: Path,
                 socket_type: str,
                 port: Optional[int] = None,
                 socket_file: Optional[Union[str, Path]] = None) -> None:
        """Initializes socket server.

        Args:
            model_config: Path to the config file.
            socket_type: Socket family. "TCP" for the AF_INET socket server, "UNIX" for UNIX Domain Socket server.
            port: Port number for the AF_INET address family. If parameter is not defined, the port number from the
                utils/settings/server_config.json is used.
            socket_file: Path to the file to which UNIX Domain Socket server connects. If parameter is not defined,
                the path from the utils/settings/server_config.json is used.

        Raises:
            ValueError: If ``socket_type`` parameter is neither "TCP" nor "UNIX".

        """
        server_params = get_server_params(model_config)
        socket_type = socket_type or server_params['socket_type']
        self._loop = asyncio.get_event_loop()

        if socket_type == 'TCP':
            host = server_params['host']
            port = port or server_params['port']
            self._launch_msg = f'{server_params["socket_launch_message"]} http://{host}:{port}'
            self._loop.create_task(asyncio.start_server(self._handle_client, host, port))
        elif socket_type == 'UNIX':
            socket_file = socket_file or server_params['unix_socket_file']
            socket_path = Path(socket_file).resolve()
            if socket_path.exists():
                socket_path.unlink()
            self._launch_msg = f'{server_params["socket_launch_message"]} {socket_file}'
            self._loop.create_task(asyncio.start_unix_server(self._handle_client, socket_file))
        else:
            raise ValueError(f'socket type "{socket_type}" is not supported')

        self._model = build_model(model_config)
        self._model_args_names = server_params['model_args_names'] 
開發者ID:deepmipt,項目名稱:DeepPavlov,代碼行數:42,代碼來源:socket.py

示例14: run

# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import start_unix_server [as 別名]
def run(self) -> None:
        server = await asyncio.start_unix_server(
            connection_handler(self.rpc.execute),
            str(self.ipc_path),
            limit=MAXIMUM_REQUEST_BYTES,
        )
        self.logger.info('IPC started at: %s', self.ipc_path.resolve())
        try:
            await self.manager.wait_finished()
        finally:
            server.close()
            self.ipc_path.unlink() 
開發者ID:ethereum,項目名稱:trinity,代碼行數:14,代碼來源:ipc.py

示例15: unixlisten

# 需要導入模塊: import asyncio [as 別名]
# 或者: from asyncio import start_unix_server [as 別名]
def unixlisten(path, onlink):
    '''
    Start an PF_UNIX server listening on the given path.
    '''
    info = {'path': path, 'unix': True}

    async def onconn(reader, writer):
        link = await Link.anit(reader, writer, info=info)
        link.schedCoro(onlink(link))
    return await asyncio.start_unix_server(onconn, path=path) 
開發者ID:vertexproject,項目名稱:synapse,代碼行數:12,代碼來源:link.py


注:本文中的asyncio.start_unix_server方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。