Called when the WebSocket connection is closed
330140
public void finish() {

		try {

			FileChannel channel = getChannel(false);

			if (channel != null && channel.isOpen()) {

				channel.force(true);
				channel.close();

				this.privateFileChannel = null;

				//file.increaseVersion();
				file.notifyUploadCompletion();
			}

		} catch (IOException e) {

			logger.warn("Unable to finish file upload", e);
		}
	}
1206025
public void onReadFailure(Throwable t) {
        ConnectionState event = null;
        synchronized (this) {
            if (this.state == ConnectionState.CLOSED) {
                // already closed
                return;
            }

            // Build out Close Reason
            String reason = "WebSocket Read Failure";
            if (t instanceof EOFException) {
                reason = "WebSocket Read EOF";
                Throwable cause = t.getCause();
                if ((cause != null) && (StringUtils.hasText(cause.getMessage()))) {
                    reason = "EOF: " + cause.getMessage();
                }
            } else {
                if (StringUtils.hasText(t.getMessage())) {
                    reason = t.getMessage();
                }
            }

            CloseInfo close = new CloseInfo(StatusCode.ABNORMAL, reason);

            finalClose.compareAndSet(null, close);

            this.cleanClose = false;
            this.state = ConnectionState.CLOSED;
            this.closeInfo = close;
            this.inputAvailable = false;
            this.outputAvailable = false;
            this.closeHandshakeSource = CloseHandshakeSource.ABNORMAL;
            event = this.state;
        }
        notifyStateListeners(event);
    }
1189719
function() {
        if(this._conn.connected && !this._conn.disconnecting) {
            Strophe.error("Websocket closed unexcectedly");
            this._conn._doDisconnect();
        } else {
            Strophe.info("Websocket closed");
        }
    }
1293777
@Override
    public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
        endpoint.onDisconnected();
        super.channelClosed(ctx, e);
    }
170921
function() {
        try {
          if (socket && socket.readyState == 1) {
            return;
          }

          socket = new WebSocket(address, []);

          socketRealTimeStatusInterval && clearInterval(socketRealTimeStatusInterval);
          socketRealTimeStatusInterval = setInterval(function() {
            switch (socket.readyState) {
              case 2:
                onCloseHandler(null);
                break;
              case 3:
                socketRealTimeStatusInterval && clearInterval(socketRealTimeStatusInterval);
                break;
            }
          }, 5000);

          socket.onopen = function(event) {
            waitForSocketToConnect(function() {
              eventCallback["open"]();
            });
          }

          socket.onmessage = function(event) {
            var messageData = JSON.parse(event.data);
            eventCallback["message"](messageData);

            /**
             * To avoid manually closing socket's connection
             */
            forceCloseSocket = false;

            socketCloseTimeout && clearTimeout(socketCloseTimeout);
            forceCloseTimeout && clearTimeout(forceCloseTimeout);

            socketCloseTimeout = setTimeout(function() {
              /**
               * If message's type is not 5, socket won't get any acknowledge packet,therefore
               * you may think that connection has been closed and you would force socket
               * to close, but before that you should make sure that connection is actually closed!
               * for that, you must send a ping message and if that message don't get any
               * responses too, you are allowed to manually kill socket connection.
               */
              ping();

              /**
               * We set forceCloseSocket as true so that if your ping's response don't make it
               * you close your socket
               */
              forceCloseSocket = true;

              /**
               * If type of messages are not 5, you won't get ant ACK packets
               * for that being said, we send a ping message to be sure of
               * socket connection's state. The ping message should have an
               * ACK, if not, you're allowed to close your socket after
               * 4 * [connectionCheckTimeout] seconds
               */
              forceCloseTimeout = setTimeout(function() {
                if (forceCloseSocket) {
                  socket.close();
                }
              }, connectionCheckTimeout);

            }, connectionCheckTimeout * 1.5);
          }

          socket.onclose = function(event) {
            onCloseHandler(event);
          }

          socket.onerror = function(event) {
            eventCallback["error"](event);
          }
        } catch (error) {
          eventCallback["customError"]({
            errorCode: 4000,
            errorMessage: "ERROR in WEBSOCKET!",
            errorEvent: error
          });
        }
      }
434749
function(newState) {
          switch (newState) {
            case 'disconnected':
            case 'error':
              webSocket = null;
              if (onClose) {
                var error;
                if(hasLostConnectivity()) {
                  error = new Error(wsCloseErrorCodes[4001]);
                  error.code = 4001;
                }
                onClose(error);
              }
              break;
          }
        }
854052
async def ensure_closed(self):
        """"""
        if self._writer is None:
            # connection has been closed
            return
        send_data = struct.pack('<i', 1) + int2byte(COMMAND.COM_QUIT)
        self._writer.write(send_data)
        await self._writer.drain()
        self.close()
568724
def socket_close(self):
        """"""
        if self.sock != NC.INVALID_SOCKET:
            self.sock.close()
        self.sock = NC.INVALID_SOCKET
46273
private void onConnectionClosed()
   {
      ConnectionEvent evt = new ConnectionEvent(this, ConnectionEvent.CONNECTION_CLOSED);
      for (ConnectionEventListener listener : listeners)
      {
         try
         {
            listener.connectionClosed(evt);
         }
         catch (Exception e1)
         {
            LOG.warn("An error occurs while notifying the listener " + listener, e1);
         }
      }
   }
363129
def on_close(self):
        
        self._stop_update_flag = True
        for ws in self.websockets:
            ws.close()
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)
1198847
@Override
    public void close() {
        if (closed)
            return;
        closed = true;
        tcpSocketConsumer.prepareToShutdown();

        if (shouldSendCloseMessage)

            eventLoop.addHandler(new EventHandler() {
                @Override
                public boolean action() throws InvalidEventHandlerException {
                    try {
                        TcpChannelHub.this.sendCloseMessage();
                        tcpSocketConsumer.stop();
                        closed = true;

                        if (LOG.isDebugEnabled())
                            Jvm.debug().on(getClass(), "closing connection to " + socketAddressSupplier);

                        while (clientChannel != null) {

                            if (LOG.isDebugEnabled())
                                Jvm.debug().on(getClass(), "waiting for disconnect to " + socketAddressSupplier);
                        }
                    } catch (ConnectionDroppedException e) {
                        throw new InvalidEventHandlerException(e);
                    }

                    // we just want this to run once
                    throw new InvalidEventHandlerException();
                }

                @NotNull
                @Override
                public String toString() {
                    return TcpChannelHub.class.getSimpleName() + "..close()";
                }
            });
    }
1159923
@Handler(channels = EncryptedChannel.class)
    public void onClosed(Closed event, IOSubchannel encryptedChannel)
            throws SSLException, InterruptedException {
        @SuppressWarnings("unchecked")
        final Optional<PlainChannel> plainChannel
            = (Optional<PlainChannel>) LinkedIOSubchannel
                .downstreamChannel(this, encryptedChannel);
        if (plainChannel.isPresent()) {
            plainChannel.get().upstreamClosed();
        }
    }
914303
function socketOnClose() {
  const websocket = this[kWebSocket];

  this.removeListener('close', socketOnClose);
  this.removeListener('end', socketOnEnd);

  websocket.readyState = WebSocket.CLOSING;

  //
  // The close frame might not have been received or the `'end'` event emitted,
  // for example, if the socket was destroyed due to an error. Ensure that the
  // `receiver` stream is closed after writing any remaining buffered data to
  // it. If the readable side of the socket is in flowing mode then there is no
  // buffered data as everything has been already written and `readable.read()`
  // will return `null`. If instead, the socket is paused, any possible buffered
  // data will be read as a single chunk and emitted synchronously in a single
  // `'data'` event.
  //
  websocket._socket.read();
  websocket._receiver.end();

  this.removeListener('data', socketOnData);
  this[kWebSocket] = undefined;

  clearTimeout(websocket._closeTimer);

  if (
    websocket._receiver._writableState.finished ||
    websocket._receiver._writableState.errorEmitted
  ) {
    websocket.emitClose();
  } else {
    websocket._receiver.on('error', receiverOnFinish);
    websocket._receiver.on('finish', receiverOnFinish);
  }
}
257811
@Override
    public void processConnect(WebSocketChannel channel, WSURI uri, String[] protocols) {
        LOG.entering(CLASS_NAME, "connect", channel);
        
        if (((WebSocketSelectedChannel)channel).readyState == ReadyState.CLOSED) {
            throw new IllegalStateException("WebSocket is already closed");
        }
        
        nextHandler.processConnect(channel, uri, protocols);
    }
840256
private void fireConnectionClosed() {
        assertUnlocked();

        BOSHClientConnEvent event = null;
        for (BOSHClientConnListener listener : connListeners) {
            if (event == null) {
                event = BOSHClientConnEvent.createConnectionClosedEvent(this);
            }
            try {
                listener.connectionEvent(event);
            } catch (Exception ex) {
                LOG.log(Level.WARNING, UNHANDLED, ex);
            }
        }
    }
1168181
void onReadingThreadFinished(WebSocketFrame closeFrame)
    {
        synchronized (mThreadsLock)
        {
            mReadingThreadFinished = true;
            mServerCloseFrame = closeFrame;

            if (mWritingThreadFinished == false)
            {
                // Wait for the writing thread to finish.
                return;
            }
        }

        // Both the reading thread and the writing thread have finished.
        onThreadsFinished();
    }