If we are going to connect to STT through websockets then its going to disconnect or timeout, so need to handle that occurrence.
165911
function connectIfNeeded() {
      // console.log('re-establishing the connect');
      websocket = null;
      socketCreationInProcess = false;

      // The token may have expired so test for it.
      getToken(determineService())
        .then(() => {
          return processSTTSocketStart(false);
        })
        .then(() => {
          //return Promise.resolve();
          return;
        })
        .catch((err) => {
          //return Promise.resolve();
          return;
        });
    }
185549
function _connect() {
        if (!_isDisconnected()) {
            var bayeuxMessage = {
                id: _nextMessageId(),
                channel: '/meta/connect',
                connectionType: _transport.getType()
            };

            // In case of reload or temporary loss of connection
            // we want the next successful connect to return immediately
            // instead of being held by the server, so that connect listeners
            // can be notified that the connection has been re-established
            if (!_connected) {
                bayeuxMessage.advice = { timeout: 0 };
            }

            _setStatus('connecting');
            _cometd._debug('Connect sent', bayeuxMessage);
            _send(false, [bayeuxMessage], true, 'connect');
            _setStatus('connected');
        }
    }
146510
function disconnect(conn, socket, err) {
  //console.dir('disconnect');

  // clean monitor listeners
  if(this._monitor[conn.id]) {
    this.removeListener('monitor', this._monitor[conn.id]);
    delete this._monitor[conn.id];
  }

  this._state.removeConnection(conn);
}
402609
public void handleLostConnection() {
        try {
            clientEngine.applySelector(ClientSelectors.any());
        } catch (Exception e) {
            LOGGER.warning("Could not clean up client B/W list filtering.", e);
        }
    }
412051
public void connect() {
        try {
            ws.setPingInterval(pingInterval);
            ws.connect();
        } catch (WebSocketException e){
            e.printStackTrace();
            if(onErrorListener != null) {
                onErrorListener.onError(e);
            }
            if(tryReconnection) {
                if (timer == null) {
                    // this is to handle reconnection first time
                    if (lastPongAt == 0) {
                        lastPongAt = 1;
                    }
                    timer = new Timer();
                    timer.scheduleAtFixedRate(getTask(), 0, pongCheckInterval);
                }
            }
        }
    }
714056
function handleConnection(socket) { // server 'connect'
		socket.setEncoding('utf-8')
		socket.on('data', requestResponder)

		function requestResponder(data) {
			socket.end(String(process.pid))
			self.emit('data', data)
		}
	}
419029
private void executeReconnect() throws InterruptedException {
		// Close connection
		websocketEndpoint.close();

		// Store the reconnect time to prevent to much
		// reconnects in a short timeframe. Otherwise the
		// rate limit will apply and the reconnects are not successfully
		logger.info("Wait for next reconnect timeslot");
		eventsInTimeslotManager.recordNewEvent();
		eventsInTimeslotManager.waitForNewTimeslot();
		logger.info("Wait for next reconnect timeslot DONE");

		bitfinexApiBroker.reconnect();
	}
378363
public synchronized void doStop() {
        if(_connection != null) {
            delegate.getLogger().debug("stomp: closing connection to remote broker");
            try {transmit(CMD_DISCONNECT, null, null, null, null);} catch (IOException ioe) {/* ignore it */}
            final IStreamConnection c= _connection;
            _connection= null;
            c.close();
            
            try {
                _receiver.stop();
                _receiver.waitForState(2000, AbstractSingleThreadRunner.STOPPED);
            } catch (InterruptedException ie) {
                delegate.getLogger().warn("stomp: could not stop receiver", ie);
            }
            
            _transformer= null;
        }
    }
1310197
@Override
    public void processConnect(WebSocketChannel channel, WSURI location, String[] protocols) {
        LOG.entering(CLASS_NAME, "connect", channel);

        nextHandler.processConnect(channel, location, protocols);
    }
1282907
def disconnect(self, device):
        """"""
        self.device.ctrl.sendcontrol('d')
        self.device.ctrl.send("c.")
        self.log("CONSOLE SERVER disconnect")
        try:
            self.device.ctrl.send(chr(4))
        except OSError:
            self.log("Protocol already disconnected")
1198483
function handleDisconnect() {
    _connection = _mysql.createConnection(_dbConfig);

    _connection.connect(function (err) {
        if (err) {
            console.log('error when connecting to db:', err);
            setTimeout(handleDisconnect, 2000);
        }
    });

    _connection.on('error', function (err) {
        console.log('db error', err);
        if (err.code === 'PROTOCOL_CONNECTION_LOST') {
            handleDisconnect();
        } else {
            throw err;
        }
    });
}
395676
function handleConnection(client) {
        // set ghostmode callbacks
        if (bs.options.get("ghostMode")) {
            addGhostMode(client);
        }

        client.emit("connection", bs.options.toJS()); //todo - trim the amount of options sent to clients

        emitter.emit("client:connected", {
            ua: client.handshake.headers["user-agent"]
        });
    }
180531
public void disconnect(){
        if(timer != null){
            timer.cancel();
        }
        if (ws != null && ws.isOpen()) {
            ws.disconnect();
            subscribedTokens = new HashSet<>();
            modeMap.clear();
        }
    }
1091492
def _on_connect_error(self, sock, err):  # pylint: disable=unused-argument
        """"""
        if isinstance(err, SystemExit):
            self.log.error(f"Shutting down websocket connection")
        else:
            self.log.error(f"Websocket error: {err}")
642969
@Override
    public void processConnect(WebSocketChannel channel, WSURI location, String[] protocols) {
        nextHandler.processConnect(channel, location, protocols);
    }
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);
  }
}
1220444
function connect(socketURL) {
        disconnect().done(function () {
            _socket = new WebSocket(socketURL);
            _socket.onmessage = _onMessage;
            _socket.onopen = _onConnect;
            _socket.onclose = _onDisconnect;
            _socket.onerror = _onError;
        });
    }