Connect with a coroutine, which is scheduled when connection is made.

        This function will create a task, and when connection is closed,
        the task will be canceled.
        :param handler:
        :return: None
181399
def set_handler(self, handler):
        
        if self._handler:
            raise Exception('Handler was already set')
        if handler:
            self._handler = async_task(handler, loop=self._loop)
1089179
async def _close(self) -> None:
        
        # Stop accepting new connections.
        self.server.close()

        # Wait until self.server.close() completes.
        await self.server.wait_closed()

        # Wait until all accepted connections reach connection_made() and call
        # register(). See https://bugs.python.org/issue34852 for details.
        await asyncio.sleep(0)

        # Close open connections. fail_connection() will cancel the transfer
        # data task, which is expected to cause the handler task to terminate.
        for websocket in self.websockets:
            if websocket.state is State.OPEN:
                websocket.fail_connection(1001)

        # asyncio.wait doesn't accept an empty first argument.
        if self.websockets:
            # The connection handler can terminate before or after the
            # connection closes. Wait until both are done to avoid leaking
            # running tasks.
            # TODO: it would be nicer to wait only for the connection handler
            # and let the handler wait for the connection to close.
            await asyncio.wait(
                [websocket.handler_task for websocket in self.websockets]
                + [
                    websocket.close_connection_task
                    for websocket in self.websockets
                    if websocket.state is State.OPEN
                ],
                loop=self.loop,
            )

        # Tell wait_closed() to return.
        self.closed_waiter.set_result(None)
140402
def _connect(self):
        
        if not self.connected.is_set():
            try:
                self.lock.acquire()
                # Another thread may have connected while we were
                # waiting to acquire the lock
                if not self.connected.is_set():
                    self._do_connect()
                    if self.keepalive:
                        self._transport.set_keepalive(self.keepalive)
                    self.connected.set()
            except GerritError:
                raise
            finally:
                self.lock.release()
1336226
def _connectRelay(self, process, protocolFactory):
        
        try:
            wf = _WrappingFactory(protocolFactory)
            connector = RelayConnector(process, wf, self.timeout,
                                       self.inductor.reactor)
            connector.connect()
        except:
            return defer.fail()
        # Return a deferred that is called back when the protocol is connected.
        return wf._onConnection
310042
async def handler(self, request):
        

        def task_done(future):
            self.tasks.remove(future)
            exception = future.exception()
            if exception:
                log.warning(
                    'While processing message: {0}\nDetails: {1}'.format(
                        exception,
                        traceback.format_exc())
                )

        client = web.WebSocketResponse()
        client_id = id(client)

        # upgrade to Websockets
        await client.prepare(request)

        log.info('Opening Websocket {0}'.format(id(client)))
        log.debug('Tasks: {0}'.format(self.tasks))
        log.debug('Clients: {0}'.format(self.clients))

        try:
            log.debug('Sending root info to {0}'.format(client_id))
            await client.send_json({
                '$': {'type': CONTROL_MESSAGE, 'monitor': True},
                'root': self.call_and_serialize(lambda: self.root),
                'type': self.call_and_serialize(lambda: type(self.root))
            })
            log.debug('Root info sent to {0}'.format(client_id))
        except Exception:
            log.exception('While sending root info to {0}'.format(client_id))

        try:
            self.clients[client] = self.send_worker(client)
            # Async receive client data until websocket is closed
            async for msg in client:
                task = self.loop.create_task(self.process(msg))
                task.add_done_callback(task_done)
                self.tasks += [task]
        except Exception:
            log.exception('While reading from socket:')
        finally:
            log.info('Closing WebSocket {0}'.format(id(client)))
            await client.close()
            del self.clients[client]

        return client
608401
def connection_lost(self, exc: Exception=None):
        
        self._handlertask.cancel()

        super().connection_lost(exc)
        if self._timeout_handler:
            self._timeout_handler.cancel()
        self._transport = None
        for i, task in self.tasks.items():
            task.cancel()
        self.connections.discard(self)
        if self.debug:
            access_logger.info("lost connection", extra=self._extra)
1138364
def _get_and_set_reconnection_handler(self, new_handler):
        
        with self._reconnection_lock:
            old = self._reconnection_handler
            self._reconnection_handler = new_handler
            return old
170695
async def disconnect(self):
        

        async with self._disconnect_lock:
            if self._state == ConnectionState.DISCONNECTED:
                return

            self._set_state(ConnectionState.DISCONNECTING)

            logger.info('%s Disconnecting...', self.fingerprint)
            if self._reconnect_task:
                self._reconnect_task.cancel()
                self._reconnect_task = None

            if self._ping_task and not self._ping_task.done():
                self._ping_task.cancel()
                self._ping_task = None

            self._db = _DbMock()
            if self._transport:
                self._disconnect_waiter = _create_future(self._loop)
                self._transport.close()
                self._transport = None
                self._protocol = None

                await self._disconnect_waiter
                self._disconnect_waiter = None
                self._set_state(ConnectionState.DISCONNECTED)
            else:
                self._transport = None
                self._protocol = None
                self._disconnect_waiter = None
                self._set_state(ConnectionState.DISCONNECTED)
959477
def _dispatcher(self, connection, event):
        
        log.debug("_dispatcher: %s", event.type)

        def do_nothing(connection, event):
            return None
        method = getattr(self, "on_" + event.type, do_nothing)
        method(connection, event)
1185569
def _stop_handler(self, handler):
        
        try:
            yield from handler.stop()
        except Exception as e:
            self.logger.error(e)
221256
def on_disconnect(self=None) -> callable:
        

        def decorator(func: callable) -> Handler:
            handler = pyrogram.DisconnectHandler(func)

            if self is not None:
                self.add_handler(handler)

            return handler

        return decorator
479319
def prepare(self):
        
        super(RabbitMQRequestHandler, self).prepare()
        if self._rabbitmq_is_closed:
            self._connect_to_rabbitmq()
487294
def connection_made(self, transport):
        
        self.transport = transport
        self.transport.write(self.method.message.encode())
        self.time_out_handle = self.loop.call_later(
            TIME_OUT_LIMIT, self.time_out)
507053
def handle(self):
        
        logger = StreamHandler.logger
        logger.debug("handling requests with message handler %s " % StreamHandler.message_handler.__class__.__name__)

        message_handler = StreamHandler.message_handler

        try:
            while True:
                logger.debug('waiting for more data')
                if not message_handler.handle(self.request, StreamHandler.BUFFER_SIZE):
                    break

            logger.warning("connection closed from %s" % (self.client_address[0]))
            self.request.close()
        except:
            logger.exception("connection closed from %s" % (self.client_address[0]))
        finally:
            self.request.close()
982614
def _dispatcher(self, connection, event):
        
        super(BaseBot, self)._dispatcher(connection, event)
        for handler in self.events[event.eventtype()]:
            handler(self, connection, event)
86847
private void disconnect(final Handler<AsyncResult<Void>> doneHandler) {
    eventBus.sendWithTimeout(inAddress, new JsonObject().putString("action", "disconnect"), 5000, new Handler<AsyncResult<Message<Boolean>>>() {
      @Override
      public void handle(AsyncResult<Message<Boolean>> result) {
        if (result.failed()) {
          ReplyException failure = (ReplyException) result.cause();
          if (failure.failureType().equals(ReplyFailure.RECIPIENT_FAILURE)) {
            log.warn(String.format("%s - Failed to disconnect from %s", DefaultOutputConnection.this, context.target()), result.cause());
            new DefaultFutureResult<Void>(failure).setHandler(doneHandler);
          } else if (failure.failureType().equals(ReplyFailure.NO_HANDLERS)) {
            log.info(String.format("%s - Disconnected from %s", DefaultOutputConnection.this, context.target()));
            new DefaultFutureResult<Void>((Void) null).setHandler(doneHandler);
          } else {
            log.debug(String.format("%s - Disconnection from %s failed, retrying", DefaultOutputConnection.this, context.target()));
            disconnect(doneHandler);
          }
        } else if (result.result().body()) {
          log.info(String.format("%s - Disconnected from %s", DefaultOutputConnection.this, context.target()));
          open = false;
          new DefaultFutureResult<Void>((Void) null).setHandler(doneHandler);
        } else {
          log.debug(String.format("%s - Disconnection from %s failed, retrying", DefaultOutputConnection.this, context.target()));
          vertx.setTimer(500, new Handler<Long>() {
            @Override
            public void handle(Long timerID) {
              disconnect(doneHandler);
            }
          });
        }
      }
    });
  }
579817
def _done_handler(self, task):
        
        try:
            task.result()
        except asyncio.CancelledError:
            # normal termination
            pass
        except Exception as err:
            try:
                if self._sm_enabled:
                    self._xmlstream.abort()
                else:
                    self._xmlstream.close()
            except Exception:
                pass
            self.on_failure(err)
            self._logger.exception("broker task failed")