on browser 
wrap browser's websocket connection into one function, if the connection drop or close, try to reconnect itself.
171360
function wsConnect() {

            var typeOfConnection;

            if (location.protocol === 'https:') {
                typeOfConnection = 'wss';
            } else {
                typeOfConnection = 'ws'
            }

            self.ws = new WebSocket(typeOfConnection + '://' + location.hostname + ':' + location.port);

            self.ws.onopen = function (event) {

                //send an intial message to server and prove that the connection is built.
                self.send('connected', 'WSM: Browser confirms websocket connection.')

                reactive(self);

            };

            self.ws.onmessage = function (event) {
                // flags.binary will be set if a binary data is received.
                // flags.masked will be set if the data was masked.
                //console.log(event.data);

                self.processMessage(JSON.parse(event.data));
            };

            self.ws.onclose = function (event) {

                wsConnect();
            }
        }
1295333
@Override
  public void onFailure(WebSocket webSocket, Throwable t, Response response) {
    socketOpen = false;
    if (t instanceof Exception) {
      callback.onError((Exception) t);
    } else {
      callback.onError(new Exception(t));
    }
  }
901691
def closed(self, code, reason=None):
        """"""
        if code != 1000:
            self._error = errors.SignalFlowException(code, reason)
            _logger.info('Lost WebSocket connection with %s (%s: %s).',
                         self, code, reason)
            for c in self._channels.values():
                c.offer(WebSocketComputationChannel.END_SENTINEL)
        self._channels.clear()
        with self._connection_cv:
            self._connected = False
            self._connection_cv.notify()
674975
function fromWebSocketURL(url) {

  if (typeof WebSocket != "undefined") {
    return require("./channels/WebSocket").createChannel(url, protocol)
  }

  // indirect so that browserify won't package it
  var mod_WebSocketConnection = "./channels/WebSocketConnection"

  return require(mod_WebSocketConnection).createChannel(url, protocol)
}
530786
function doReconnect() {
    //
    // Cleanup and recreate the socket associated
    // with this instance.
    //
    self.retry.waiting = true;
    self.socket.removeAllListeners();
    self.socket = common.createSocket(self._options);

    //
    // Cleanup reconnect logic once the socket connects
    //
    self.socket.once('connect', function () {
      self.retry.waiting = false;
      self.retry.retries = 0;
    });

    //
    // Attempt to reconnect the socket
    //
    self._setup();
    self.connect();
  }
828799
private void actuallyReconnect() {
        if (((null == signalingChannel) || !signalingChannel.connected) && reconnect) {
            if (connectionInProgress) {
                // The client app must have initiated a connection manually during the timeout period. Try again later
                performReconnect();
            } else {
                Log.d(TAG, "Trying to reconnect...");
                connect(localEndpointID, applicationID, reconnect, presence, appContext, new ConnectCompletionListener() {
                    @Override
                    public void onError(final String errorMessage) {
                        // A REST API call failed. Socket errors are handled in the onError callback
                        new Handler(Looper.getMainLooper()).post(new Runnable() {
                            @Override
                            public void run() {
                                Listener listener = listenerReference.get();
                                if (null != listener) {
                                    listener.onError(RespokeClient.this, errorMessage);
                                }
                            }
                        });

                        // Try again later
                        performReconnect();
                    }
                });
            }
        }
    }
1343309
def stop(self):
        '''
        
        '''
        try:
            if (self.websock and self.websock.sock
                    and self.websock.sock.connected):
                self.logger.info('shutting down websocket connection')
                try:
                    self.websock.close()
                except BaseException as e:
                    self.logger.error(
                            'exception closing websocket %s - %s',
                            self.websock, e)

            self.chrome.stop()

            if self.websock_thread and (
                    self.websock_thread != threading.current_thread()):
                self.websock_thread.join(timeout=30)
                if self.websock_thread.is_alive():
                    self.logger.error(
                            '%s still alive 30 seconds after closing %s, will '
                            'forcefully nudge it again', self.websock_thread,
                            self.websock)
                    self.websock.keep_running = False
                    self.websock_thread.join(timeout=30)
                    if self.websock_thread.is_alive():
                        self.logger.critical(
                                '%s still alive 60 seconds after closing %s',
                                    self.websock_thread, self.websock)

            self.websock_url = None
        except:
            self.logger.error('problem stopping', exc_info=True)
892627
def receive(self):
        
        if self._closed:
            raise WebSocketError("Connection is already closed")
        try:
            return self.read_message()
        except UnicodeError as e:
            logger.info('websocket.receive: UnicodeError {}'.format(e))
            self.close(1007)
        except WebSocketError as e:
            logger.info('websocket.receive: WebSocketError {}'.format(e))
            self.close(1002)
        except Exception as e:
            logger.info('websocket.receive: Unknown error {}'.format(e))
            raise e
314584
function tryReconnect() {
    self.retry.retries++;
    if (self.retry.retries >= self.retry.max) {
      return self.emit('error', new Error('Did not reconnect after maximum retries: ' + self.retry.max));
    }

    doReconnect();
  }
500886
function connectToURL(url) {
        if (_connectDeferred) {
            // reject an existing connection attempt
            _connectDeferred.reject("CANCEL");
        }
        var deferred = new $.Deferred();
        _connectDeferred = deferred;
        var promise = getDebuggableWindows();
        promise.done(function onGetAvailableSockets(response) {
            var i, page;
            for (i in response) {
                page = response[i];
                if (page.webSocketDebuggerUrl && page.url.indexOf(url) === 0) {
                    connect(page.webSocketDebuggerUrl);
                    // _connectDeferred may be resolved by onConnect or rejected by onError
                    return;
                }
            }
            deferred.reject(FileError.ERR_NOT_FOUND); // Reject with a "not found" error
        });
        promise.fail(function onFail(err) {
            deferred.reject(err);
        });
        return deferred.promise();
    }
478175
async def poll_event(self):
        
        try:
            msg = await self.recv()
            await self.received_message(msg)
        except websockets.exceptions.ConnectionClosed as exc:
            if self._can_handle_close(exc.code):
                log.info('Websocket closed with %s (%s), attempting a reconnect.', exc.code, exc.reason)
                raise ResumeWebSocket(self.shard_id) from exc
            else:
                log.info('Websocket closed with %s (%s), cannot reconnect.', exc.code, exc.reason)
                raise ConnectionClosed(exc, shard_id=self.shard_id) from exc
310163
function() {
  EventEmitter.call(this);
  this.httpServer = new HttpServer();

  var self = this;
  this.wsServer = new WebSocketServer({server: this.httpServer});

  this.wsServer.on('connection', function(socket) {
    // emit socket to outside
    self.emit('connection', socket);
  });

  this.state = ST_STARTED;
}
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}")
613553
def reconnect_backoff(attempt)
      if attempt > 16
        backoff = RECONNECT_BACKOFF
      else
        backoff = [RECONNECT_BACKOFF, CONNECT_INTERVAL * 2 ** attempt].min
      end

      backoff *= rand
    end
285424
def _get_websocket(self, reuse=True):
        
        # Check if still connected
        if self.ws and reuse:
            if self.ws.connected:
                return self.ws

            logging.debug("Stale connection, reconnecting.")

        self.ws = self._create_connection()
        return self.ws
932688
function wrapNodeSocket(ws, reportError) {
  // Data traveling from websocket to consumer
  var incoming = makeChannel();
  // Data traveling from consumer to websocket
  var outgoing = makeChannel();

  onTake = wrapHandler(onTake, onError);
  outgoing.take(onTake);

  ws.onerror = onError;
  ws.onmessage = wrap(onMessage, onError);
  ws.onclose = wrap(onClose, onError);

  function onError(err) {
    if (reportError) return reportError(err);
    console.error(err.stack);
  }

  function onMessage(evt) {
    if (evt.data instanceof ArrayBuffer) {
      incoming.put(new Uint8Array(evt.data));
    }
  }

  function onClose(evt) {
    incoming.put();
  }

  function onTake(data) {
    // console.log("TAKE", data);
    if (data === undefined) {
      ws.close();
      return;
    }
    ws.send(data);
    outgoing.take(onTake);
  }

  return {
    put: outgoing.put,
    drain: outgoing.drain,
    take: incoming.take,
  };
}
1024517
def ensure(self, connection, func, *args, **kwargs):
        
        channel = None
        while 1:
            try:
                if channel is None:
                    channel = connection.channel()
                return func(channel, *args, **kwargs), channel
            except (connection.connection_errors, IOError):
                self._call_errback()

            channel = self.connect(connection)