Handle closing the socket channel with appropriate debug and error
protection.

@param sc
436388
private void closeSocketChannel(SocketChannel sc) {

        if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) {
            try {
                Tr.event(this, tc, "Closing connection, local: " + sc.socket().getLocalSocketAddress() + " remote: " + sc.socket().getRemoteSocketAddress());
            } catch (Throwable t) {
                // protect against JDK PK42970 throwing illegal arg
            }
        }

        try {
            sc.close();
        } catch (IOException ioe) {

            if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) {
                Tr.event(this, tc, "IOException caught while closing connection " + ioe);
            }
        }
    }
499137
public void close() {

		boolean performClose = false;
		;

		synchronized (this) {
			if (!closing && state == CHANNEL_OPEN) {
				performClose = closing = true;
			}
		}

		if (performClose) {

			synchronized (listeners) {
				for (Enumeration<ChannelEventListener> e = listeners.elements(); e
						.hasMoreElements();) {
					(e.nextElement()).channelClosing(this);
				}
			}

			try {
				// Close the ChannelOutputStream
				out.close(!isLocalEOF);

				// Send our close message
				ByteArrayWriter msg = new ByteArrayWriter(5);
				msg.write(SSH_MSG_CHANNEL_CLOSE);
				msg.writeInt(remoteid);

				try {
					if (Log.isDebugEnabled()) {
						Log.debug(this,
								"Sending SSH_MSG_CHANNEL_CLOSE id=" + channelid
										+ " rid=" + remoteid);
					}
					connection.sendMessage(msg.toByteArray(), true);
				} catch (SshException ex1) {
					if (Log.isDebugEnabled()) {
						Log.debug(this,
								"Exception attempting to send SSH_MSG_CHANNEL_CLOSE id="
										+ channelid + " rid=" + remoteid, ex1);
					}
				} finally {
					msg.close();
				}

				this.state = CHANNEL_CLOSED;

			} catch (EOFException eof) {
				// Ignore this is the message store informing of close/eof
			} catch (SshIOException ex) {
				if (Log.isDebugEnabled()) {
					Log.debug(this,
							"SSH Exception during close reason="
									+ ex.getRealException().getReason()
									+ " id=" + channelid + " rid=" + remoteid,
							ex.getRealException());
				}
				// IO Error during close so the connection has dropped
				connection.transport.disconnect(
						TransportProtocol.CONNECTION_LOST,
						"IOException during channel close: " + ex.getMessage());
			} catch (IOException ex) {
				if (Log.isDebugEnabled()) {
					Log.debug(this, "Exception during close id="
							+ channelid + " rid=" + remoteid, ex);
				}
				// IO Error during close so the connection has dropped
				connection.transport.disconnect(
						TransportProtocol.CONNECTION_LOST,
						"IOException during channel close: " + ex.getMessage());
			} finally {
				checkCloseStatus(ms.isClosed());
			}
		}
	}
175237
void close() {
        try {
            performTeardownExchange();
        } catch (IOException e) {
            logger.warn("Problem reporting our intention to close the dbserver connection", e);
        }
        try {
            channel.close();
        } catch (IOException e) {
            logger.warn("Problem closing dbserver client output channel", e);
        }
        try {
            os.close();
        } catch (IOException e) {
            logger.warn("Problem closing dbserver client output stream", e);
        }
        try {
            is.close();
        } catch (IOException e) {
            logger.warn("Problem closing dbserver client input stream", e);
        }
        try {
            socket.close();
        } catch (IOException e) {
            logger.warn("Problem closing dbserver client socket", e);
        }
    }
1362335
public static void closeConnection( Channel channel ) throws IOException {

		if( channel != null ) {
			if( channel.isOpen())
				channel.close();

			if( channel.getConnection().isOpen())
				channel.getConnection().close();
		}
	}
851489
protected void close()
    {
        assert (fd != null);
        try {
            fd.close();
            socket.eventClosed(addr.toString(), fd);
        }
        catch (IOException e) {
            socket.eventCloseFailed(addr.toString(), ZError.exccode(e));
        }
        fd = null;
    }
1234468
private void prepSocketChannel(SocketChannel sc) {
        try {
            sc.socket().setSendBufferSize(1024 * 1024 * 2);
            sc.socket().setReceiveBufferSize(1024 * 1024 * 2);
        } catch (SocketException e) {
            e.printStackTrace();
        }
    }
461306
public void close() throws IOException {
        for (;;) {
            int state = this.state;
            if (isClosed(state)) {
                return;
            }
            // Once a close operation happens, the channel is considered shutdown.
            if (casState(state, state | STATE_ALL_MASK)) {
                break;
            }
        }
        int res = close(fd);
        if (res < 0) {
            throw newIOException("close", res);
        }
    }
1246621
public void handleError(SelectableChannel channel) {
    LOG.info("Handling Error. Cleaning states in HeronClient.");
    contextMap.clear();
    responseMessageMap.clear();
    messageMap.clear();
    socketChannelHelper.clear();
    nioLooper.removeAllInterest(channel);

    try {
      channel.close();
      LOG.info("Successfully closed the channel: " + channel);
    } catch (IOException e) {
      LOG.log(Level.SEVERE, "Failed to close connection in handleError", e);
    }

    // Since we closed the channel, we set isConnected false
    isConnected = false;
    onError();
  }
656945
@Override
    public synchronized void processClose(WebSocketChannel channel, int code, String reason) {
        nextHandler.processClose(channel, code, reason);        
    }
70504
@Handler(channels = NetworkChannel.class)
    public void onClosed(Closed event, TcpChannel netConnChannel) {
        netConnChannel.associated(WebAppMsgChannel.class).ifPresent(
            appChannel -> appChannel.handleClosed(event));
        pooled.remove(netConnChannel.remoteAddress(), netConnChannel);
    }
1203296
public void stop(long millisec) throws ChannelException {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
            Tr.entry(this, tc, "stop " + millisec + "; " + getName());
        }
        // only stop the channel if millisec is 0, otherwise ignore.
        if (millisec == 0) {
            stoppedFlag = true;

            // Stop accepting new connections on the inbound channels
            if (getConfig().isInboundChannel()) {

                try {
                    Tr.info(tc, "CWUDP0002I", new Object[] { getConfig().getExternalName(), displayableHostName, String.valueOf(getConfig().getPort()) });
                } catch (Exception e) {
                    // just debug,since this is on an audit attempt
                    if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                        Tr.debug(this, tc, "Got exception auditing UDP Channel Stop: " + e);
                    }
                }
            }

            // destroy all the "in use" UDPConnLink. This should close all
            // the sockets held by these connections.
            destroyConnLinks();

        }
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
            Tr.exit(this, tc, "stop");
        }
    }
416437
@Override
    public void close() throws IOException
    {
        if (!isClosed)
        {
            flush();
            if (closeChannel)
            {
                channel.close();
            }
            isClosed = true;
        }
    }
1132878
public static void closeClient(TServiceClient client) {
        if (client == null) {
            return;
        }
        try {
            TProtocol proto = client.getInputProtocol();
            if (proto != null) {
                proto.getTransport().close();
            }
        } catch (Throwable e) {
            logger.warn("close input transport fail", e);
        }
        try {
            TProtocol proto = client.getOutputProtocol();
            if (proto != null) {
                proto.getTransport().close();
            }
        } catch (Throwable e) {
            logger.warn("close output transport fail", e);
        }

    }
1241643
void closedHandler(Object context, String input, Object frame, String stateName) {
        if (getReadyState() == ReadyState.CLOSED) {
            return;
        }
        
        // TODO: Determine whether channels need to be cleaned up.
        if (this.channels.size() != 0) {
            for (int i = 1; i <= this.channels.size(); i++) { // 1-based
                AmqpChannel channel = this.channels.get(i);
                AmqpFrame   f = new AmqpFrame();
                
                // Close each channel which should result in CLOSE event
                // to be fired for each of the registered ChannelListener(s).
                f.setMethodName("closeChannel");
                f.setChannelId((short) i);
                channel.channelClosedHandler(this, "", f, "closeChannel");
            }
        }
        
        try {
            // Mark the readyState to be CLOSED.
            readyState = ReadyState.CLOSED;
            
            // Fire CLOSE event for the ConnectionListener(s) registered
            // on AmqpClient object.
            fireOnClosed(new ConnectionEvent(this, Kind.CLOSE));

            // If the WebSocket(or ByteSocket) is still not closed, then 
            // invoke the close() method. The callback in this case will be a
            // a no-op as we have completed the book-keeping here.
            if (websocket != null) {
                websocket.close();
            }
        }
        catch (Exception e1) {
            throw new IllegalStateException(e1);
        }
        finally {
            websocket = null;
        }

    }
527641
public void close()
    {
    if (_socket!=null) {
        try {
        _socket.close();
        _socket = null;
        } catch (IOException e) {
        System.err.println("Exception: " + e);
        // throw new SoccomException(SoccomException.RECV_ERROR);
        }
        _in = null;
        _out = null;
    }
    }
1010101
protected void safeClose () {
        Session closeSession = this.socketSession;
        this.socketSession = null;

        try {
            if (closeSession != null) {
                //
                // Remove from the registry first in case the close blocks for a while.  Doing so prevents additional
                // errors logged for attempts to send to this now-defunct websocket.
                //
                registry.remove(this.socketSessionId);
                closeSession.close();
            }
        } catch (IOException ioExc) {
            log.debug("io exception on safe close of session", ioExc);
        }
    }
130923
@Override
    public void close() throws IOException {
        if(UndertowLogger.REQUEST_IO_LOGGER.isTraceEnabled()) {
            UndertowLogger.REQUEST_IO_LOGGER.tracef(new ClosedChannelException(), "Channel %s is being closed", this);
        }
        safeClose(channel);
        if(readData != null) {
            readData.close();
            readData = null;
        }
        closeSubChannels();
    }