当前位置: 首页>>代码示例>>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;未经允许,请勿转载。