Close the connection by handshaking with the server.

        This method is a :ref:`coroutine <coroutine>`.
967879
def close(self):
        
        if not self.is_closed():
            self._closing = True
            # Let the ConnectionActor do the actual close operations.
            # It will do the work on CloseOK
            self.sender.send_Close(
                0, 'Connection closed by application', 0, 0)
            try:
                yield from self.synchroniser.wait(spec.ConnectionCloseOK)
            except AMQPConnectionError:
                # For example if both sides want to close or the connection
                # is closed.
                pass
        else:
            if self._closing:
                log.warn("Called `close` on already closing connection...")
        # finish all pending tasks
        yield from self.protocol.heartbeat_monitor.wait_closed()
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)
678483
async def close_async(self):
        
        if self.message_handler:
            await self.message_handler.destroy_async()
            self.message_handler = None
        self._shutdown = True
        if self._keep_alive_thread:
            await self._keep_alive_thread
            self._keep_alive_thread = None
        if not self._session:
            return  # already closed.
        if not self._connection.cbs:
            _logger.info("Closing non-CBS session.")
            await asyncio.shield(self._session.destroy_async())
        else:
            _logger.info("CBS session pending %r.", self._connection.container_id)
        self._session = None
        if not self._ext_connection:
            _logger.info("Closing exclusive connection %r.", self._connection.container_id)
            await asyncio.shield(self._connection.destroy_async())
        else:
            _logger.info("Shared connection remaining open.")
        self._connection = None
605281
public void close() {
        done = true;
        connected = false;
        synchronized (this) {
            try {
                if (socket != null) {
                    if (traceLevel >= ctrlThreshold) {
                        System.out.println("-> CLOSE");
                    }
                    socket.close();
                }
            } catch (final IOException e) { /* ignore socket close errors */
            } finally {
                socket = null;
            }
        }
    }
287028
def close(self):
        
        if self._recv_task:
            self._recv_task.cancel()

        self._disable_monitoring()

        if self._monitor_task and not self._monitor_task.done():
            self._monitor_task.cancel()

        self._receiver.cancel()
        self._socket.close(linger=0)

        self._msg_router.fail_all(DisconnectError())
398040
def close(self):
        
        if self._closed:
            return
        try:
            with self.lock:
                if not self._closed:
                    self._closed = True
                    for address in list(self.connections):
                        self.remove(address)
        except TypeError as e:
            pass
1371727
public void close(int statusCode, HandshakeResponse errResponse) {
        log.warn("Closing connection with status: {}", statusCode);
        // remove handshake flag
        session.removeAttribute(Constants.HANDSHAKE_COMPLETE);
        // clear the delay queue
        queue.clear();
        // send http error response
        session.write(errResponse);
        // whether to attempt a nice close or a forceful one
        if (WebSocketTransport.isNiceClose()) {
            // now send close packet with error code
            IoBuffer buf = IoBuffer.allocate(16);
            buf.setAutoExpand(true);
            // all errors except 403 will use 1002
            buf.putUnsigned((short) statusCode);
            try {
                if (statusCode == 1008) {
                    // if its a 403 forbidden
                    buf.put("Policy Violation".getBytes("UTF8"));
                } else {
                    buf.put("Protocol error".getBytes("UTF8"));
                }
            } catch (Exception e) {
                // shouldnt be any text encoding issues...
            }
            buf.flip();
            byte[] errBytes = new byte[buf.remaining()];
            buf.get(errBytes);
            // construct the packet
            Packet packet = Packet.build(errBytes, MessageType.CLOSE);
            WriteFuture writeFuture = session.write(packet);
            writeFuture.addListener(new IoFutureListener<WriteFuture>() {

                @Override
                public void operationComplete(WriteFuture future) {
                    if (future.isWritten()) {
                        log.debug("Close message written");
                        // only set on success for now to skip boolean check later
                        session.setAttribute(Constants.STATUS_CLOSE_WRITTEN, Boolean.TRUE);
                    }
                    future.removeListener(this);
                }

            });
            // adjust close routine to allow for flushing
            CloseFuture closeFuture = session.closeOnFlush();
            closeFuture.addListener(new IoFutureListener<CloseFuture>() {

                public void operationComplete(CloseFuture future) {
                    if (future.isClosed()) {
                        log.debug("Connection is closed");
                    } else {
                        log.debug("Connection is not yet closed");
                    }
                    future.removeListener(this);
                }

            });
        } else {
            // force close
            CloseFuture closeFuture = session.closeNow();
            closeFuture.addListener(new IoFutureListener<CloseFuture>() {

                public void operationComplete(CloseFuture future) {
                    if (future.isClosed()) {
                        log.debug("Connection is closed");
                    } else {
                        log.debug("Connection is not yet closed");
                    }
                    future.removeListener(this);
                }

            });
        }
        log.debug("Close complete");
    }
1266551
async def close(self, code: int = 1006, reason: str = "Connection closed"):
        
        if self._closed:
            return

        self._closed = True

        if self._scope is not None:
            await self._scope.cancel()
            # cancel any outstanding listeners

        data = self._connection.send(CloseConnection(code=code, reason=reason))
        await self._sock.send_all(data)

        # No, we don't wait for the correct reply
        await self._sock.close()
335850
public void disconnect() {
        if (readyState == ReadyState.OPEN) {
            // readyState should be set to ReadyState.CLOSED ONLY AFTER the
            // the WebSocket has been successfully closed in
            // socketClosedHandler().
            this.closeConnection(0, "", 0, 0, null, null);
        } else if (readyState == ReadyState.CONNECTING) {
            socketClosedHandler();
        }
    }
993882
def Close(self):
		
		if self.connection is not None:
			try:
				self.connection.commit()
				self.connection.close()
				self.connection = None
			except Exception, e:
				pass
1012444
public void stopConnection() throws CommunicationException, KeystoreException {
		processedFailedNotifications();
		try {
			logger.debug("Closing connection");
			this.socket.close();
		} catch (Exception e) {
			/* Do not complain if connection is already closed... */
		}
	}
9385
def close(self):
        
        if self.is_open:
            message_input = UnityMessage()
            message_input.header.status = 400
            self.unity_to_external.parent_conn.send(message_input)
            self.unity_to_external.parent_conn.close()
            self.server.stop(False)
            self.is_open = False
32437
def close(self, error=None):
        
        if self.state is ConnectionStates.DISCONNECTED:
            return
        with self._lock:
            if self.state is ConnectionStates.DISCONNECTED:
                return
            log.info('%s: Closing connection. %s', self, error or '')
            self._update_reconnect_backoff()
            self._sasl_auth_future = None
            self._protocol = KafkaProtocol(
                client_id=self.config['client_id'],
                api_version=self.config['api_version'])
            if error is None:
                error = Errors.Cancelled(str(self))
            ifrs = list(self.in_flight_requests.items())
            self.in_flight_requests.clear()
            self.state = ConnectionStates.DISCONNECTED
            # To avoid race conditions and/or deadlocks
            # keep a reference to the socket but leave it
            # open until after the state_change_callback
            # This should give clients a change to deregister
            # the socket fd from selectors cleanly.
            sock = self._sock
            self._sock = None

        # drop lock before state change callback and processing futures
        self.config['state_change_callback'](self.node_id, sock, self)
        sock.close()
        for (_correlation_id, (future, _timestamp)) in ifrs:
            future.failure(error)
774728
def close(self):
        
        self.application.client_leaving(self)

        self.conn.close()
        self.closed = True
1022926
def close(self):
        
        if hasattr(self, "thread"):
            self.thread._exit = True
            self.thread.join(1000)
        if self._conn is not None:
            self._conn.close()
264784
async def close(self):
        
        if self._conn is None:
            return
        await self._run_operation(self._impl.close)
        self._conn = None
1289364
def close(self) -> None:
        
        def _shutdown() -> None:
            self.transport.close()
            self.shutdown_event.set()

        with self._shutdown_lock:
            if not self._shutdown:
                self._shutdown = True
                self.protocol.loop.call_soon_threadsafe(_shutdown)