def connect_client(ws)
      actor = Actor.current

      # run the blocking websocket client connect+read in a separate thread
      defer {
        ws.on_pong do |delay|
          # XXX: called with the client mutex locked, do not block
          actor.async.on_pong(delay)
        end

        # blocks until open, raises on errors
        ws.connect

        # These are called from the read_ws -> defer thread, proxy back to actor
        actor.on_open

        ws.read do |message|
          actor.on_message(message)
        end
      }

    rescue Kontena::Websocket::CloseError => exc
      # server closed connection
      on_close(exc.code, exc.reason)
      disconnected!

    rescue Kontena::Websocket::Error => exc
      # handle known errors, will reconnect or shutdown
      on_error exc
      disconnected!

    rescue => exc
      # XXX: crash instead of reconnecting on unknown errors?
      error exc
      disconnected!

    else
      # impossible: agent closed connection?!
      info "Agent closed connection with code #{ws.close_code}: #{ws.close_reason}"
      disconnected!

    ensure
      ws.disconnect # close socket
    end
def connect_client(ws)
      actor = Actor.current

      # run the blocking websocket client connect+read in a separate thread
      defer {
        ws.on_pong do |delay|
          # XXX: called with the client mutex locked, do not block
          actor.async.on_pong(delay)
        end

        # blocks until open, raises on errors
        ws.connect

        # These are called from the read_ws -> defer thread, proxy back to actor
        actor.on_open

        ws.read do |message|
          actor.on_message(message)
        end
      }

    rescue Kontena::Websocket::CloseError => exc
      # server closed connection
      on_close(exc.code, exc.reason)
      disconnected!

    rescue Kontena::Websocket::Error => exc
      # handle known errors, will reconnect or shutdown
      on_error exc
      disconnected!

    rescue => exc
      # XXX: crash instead of reconnecting on unknown errors?
      error exc
      disconnected!

    else
      # impossible: agent closed connection?!
      info "Agent closed connection with code #{ws.close_code}: #{ws.close_reason}"
      disconnected!

    ensure
      ws.disconnect # close socket
    end
Connect the websocket client, and read messages.

 Keeps running as a separate defer thread as long as the websocket client is connected.

 Calls disconnected! -> reconnect! when done.

 @param ws [Kontena::Websocket::Client]