How to use the trio.socket function in trio

To help you get started, we’ve selected a few trio examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github ethereum / trinity / tests-trio / p2p-trio / test_discovery.py View on Github external
def __init__(self, bootnodes):
        privkey = keys.PrivateKey(keccak(b"seed"))
        self.messages = []
        socket = trio.socket.socket(family=trio.socket.AF_INET, type=trio.socket.SOCK_DGRAM)
        super().__init__(privkey, AddressFactory(), bootnodes, event_bus=None, socket=socket)
github ethereum / trinity / scripts / discovery.py View on Github external
async def run() -> None:
        socket = trio.socket.socket(family=trio.socket.AF_INET, type=trio.socket.SOCK_DGRAM)
        await socket.bind(('0.0.0.0', listen_port))
        async with TrioEndpoint.serve(networking_connection_config) as endpoint:
            service = DiscoveryService(privkey, addr, bootstrap_nodes, endpoint, socket)
            await TrioManager.run_service(service)
github caproto / caproto / caproto / trio / client.py View on Github external
async def _broadcaster_recv_loop(self, task_status):
        self.udp_sock = ca.bcast_socket(socket_module=socket)
        # Must bind or getsocketname() will raise on Windows.
        # See https://github.com/caproto/caproto/issues/514.
        self.udp_sock.bind(('', 0))
        self.broadcaster.our_address = safe_getsockname(self.udp_sock)
        command = self.broadcaster.register('127.0.0.1')
        await self.send(ca.EPICS_CA2_PORT, command)
        task_status.started()

        while True:
            async with self._cleanup_condition:
                if self._cleanup_event.is_set():
                    self.udp_sock.close()
                    self.log.debug('Exiting broadcaster recv loop')
                    break

            try:
github ethereum / lahja / lahja / trio / endpoint.py View on Github external
async def _run_server(self) -> None:
        async with trio.open_nursery() as nursery:
            # Store nursery on self so that we can access it for cancellation
            self._server_nursery = nursery

            self.logger.debug("%s: server starting", self)
            socket = trio.socket.socket(trio.socket.AF_UNIX, trio.socket.SOCK_STREAM)
            await socket.bind(self.ipc_path.__fspath__())
            socket.listen(self._connection_backlog)
            listener = trio.SocketListener(socket)

            async def set_socket_bound() -> None:
                self._socket_bound.set()

            # Use start_soon here so that we give serve_listeners() below a chance to run before
            # other endpoints start connecting to us.
            nursery.start_soon(set_socket_bound)

            try:
                await trio.serve_listeners(
                    handler=self._accept_conn,
                    listeners=(listener,),
                    handler_nursery=nursery,
github caproto / caproto / caproto / trio / server.py View on Github external
async def make_socket(interface, port):
                    s = trio.socket.socket()
                    await s.bind((interface, port))
                    return s
github radiasoft / sirepo / sirepo / pkcli / runner.py View on Github external
async def _main():
    pkdlog('runner daemon starting up')
    with trio.socket.socket(family=trio.socket.AF_UNIX) as sock:
        # XX TODO: better strategy for handoff between runner instances
        # Clear out any stale socket file
        sock_path = srdb.runner_socket_path()
        pkio.unchecked_remove(sock_path)
        await sock.bind(str(sock_path))
        sock.listen(_LISTEN_QUEUE)
        listener = trio.SocketListener(sock)

        async with trio.open_nursery() as nursery:
            nursery.start_soon(_tmp_dir_gc)
            job_tracker = _JobTracker(nursery)
            await trio.serve_listeners(
                functools.partial(_handle_conn, job_tracker),
                [listener],
            )
github caproto / caproto / caproto / trio / server.py View on Github external
async def broadcaster_udp_server_loop(self, task_status):
        for interface in self.interfaces:
            udp_sock = ca.bcast_socket(socket)
            self.broadcaster._our_addresses.append(udp_sock.getsockname()[:2])
            try:
                await udp_sock.bind((interface, self.ca_server_port))
            except Exception:
                self.log.exception('UDP bind failure on interface %r',
                                   interface)
                raise
            self.log.debug('UDP socket bound on %s:%d', interface,
                           self.ca_server_port)
            self.udp_socks[interface] = udp_sock

        for interface, udp_sock in self.udp_socks.items():
            self.log.debug('Broadcasting on %s:%d', interface,
                           self.ca_server_port)
            self.nursery.start_soon(self._core_broadcaster_loop, udp_sock)
github agronholm / anyio / src / anyio / _backends / _trio.py View on Github external
def _wait_writable(self):
        return wait_socket_writable(self._raw_socket)

    async def _notify_close(self):
        if self._raw_socket.fileno() >= 0:
            notify_closing(self._raw_socket)

    def _check_cancelled(self):
        return trio_lowlevel.checkpoint()

    def _run_sync_in_worker_thread(self, func: Callable, *args):
        return run_sync_in_worker_thread(func, *args)


getaddrinfo = trio.socket.getaddrinfo
getnameinfo = trio.socket.getnameinfo


async def wait_socket_readable(sock):
    try:
        await wait_readable(sock)
    except trio.ClosedResourceError as exc:
        raise ClosedResourceError().with_traceback(exc.__traceback__) from None
    except trio.BusyResourceError:
        raise ResourceBusyError('reading from') from None


async def wait_socket_writable(sock):
    try:
        await wait_writable(sock)
    except trio.ClosedResourceError as exc:
        raise ClosedResourceError().with_traceback(exc.__traceback__) from None
github ethereum / trinity / p2p / discovery.py View on Github external
bootstrap_nodes: Sequence[NodeAPI],
                 event_bus: EndpointAPI,
                 socket: trio.socket.SocketType) -> None:
        self.privkey = privkey
        self.address = address
        self.bootstrap_nodes = bootstrap_nodes
        self._event_bus = event_bus
        self.this_node = Node(self.pubkey, address)
        self.routing = RoutingTable(self.this_node)
        self.pong_callbacks = CallbackManager()
        self.ping_callbacks = CallbackManager()
        self.neighbours_callbacks = CallbackManager()
        self.parity_pong_tokens: Dict[Hash32, Hash32] = {}
        if socket.family != trio.socket.AF_INET:
            raise ValueError("Invalid socket family")
        elif socket.type != trio.socket.SOCK_DGRAM:
            raise ValueError("Invalid socket type")
        self.socket = socket