# Client (/sdks/cpp/reference/client)



The C++ SDK exposes a single `Client` class backed by one gRPC connection. Use the static `Client::Create()` factory method with `ClientOptions` to configure address, TLS, auth, retries, and observability. The client is thread-safe and non-copyable (PIMPL pattern).

## Include [#include]

```cpp
#include "kubemq/kubemq.h"
```

Requires C++17. Compatible with KubeMQ server v2.2+.

## Constructor [#constructor]

### Client::Create [#clientcreate]

```cpp
[[nodiscard]] static StatusOr<std::unique_ptr<Client>> Create(const ClientOptions& options);
```

Creates a connected client. By default, verifies connectivity with a Ping before returning (controlled by `set_check_connection()`).

**Parameters:**

| Name      | Type                   | Required | Description                           |
| --------- | ---------------------- | -------- | ------------------------------------- |
| `options` | `const ClientOptions&` | Yes      | Connection and behavior configuration |

**Returns:** `StatusOr<std::unique_ptr<Client>>` -- a connected client on success. Check `ok()` before accessing.

**Errors:** Validation, timeout, auth, or transient network errors.

> **Note:** The client is thread-safe. Share one instance across threads rather than creating a client per request.

## Lifecycle [#lifecycle]

### Close [#close]

```cpp
[[nodiscard]] Status Close();
```

Drains in-flight work (up to `drain_timeout`) and closes the gRPC connection. After `Close`, methods return `kErrClientClosed`.

**Returns:** `Status` -- OK on success, or transport close errors.

### Ping [#ping]

```cpp
[[nodiscard]] StatusOr<ServerInfo> Ping();
```

Health check against the broker. Returns server metadata when reachable.

**Returns:** `StatusOr<ServerInfo>` -- server identity, version, and uptime fields.

### State [#state]

```cpp
ConnectionState State() const;
```

Returns the current connection state (`kConnecting`, `kReady`, `kReconnecting`, `kClosed`, etc.).

## ClientOptions [#clientoptions]

| Method                            | Default           | Description                        |
| --------------------------------- | ----------------- | ---------------------------------- |
| `set_address(host, port)`         | `localhost:50000` | Broker host and gRPC port          |
| `set_client_id(id)`               | Auto-generated    | Stable client identifier           |
| `set_auth_token(token)`           | None              | JWT or API key                     |
| `set_credential_provider(p)`      | None              | Dynamic token refresh              |
| `set_tls_config(config)`          | None              | TLS/mTLS settings                  |
| `set_connection_timeout(d)`       | 10s               | Initial connection deadline        |
| `set_reconnect_policy(p)`         | Infinite retries  | Reconnect backoff and max attempts |
| `set_retry_policy(p)`             | Default           | Unary RPC retry policy             |
| `set_drain_timeout(d)`            | 5s                | Drain timeout on Close             |
| `set_keepalive_time(d)`           | 10s               | gRPC keepalive ping interval       |
| `set_keepalive_timeout(d)`        | 20s               | gRPC keepalive timeout             |
| `set_max_receive_message_size(n)` | 4 MB              | Max inbound message size           |
| `set_max_send_message_size(n)`    | 100 MB            | Max outbound message size          |
| `set_wait_for_ready(b)`           | true              | Wait for gRPC channel ready        |
| `set_check_connection(b)`         | true              | Ping on connect                    |
| `set_logger(l)`                   | None              | Custom logger                      |

### State Callbacks [#state-callbacks]

| Method                    | Description                   |
| ------------------------- | ----------------------------- |
| `set_on_connected(cb)`    | Connection established        |
| `set_on_disconnected(cb)` | Connection lost               |
| `set_on_reconnecting(cb)` | Reconnection attempt starting |
| `set_on_reconnected(cb)`  | Reconnection succeeded        |
| `set_on_closed(cb)`       | Client permanently closed     |
| `set_on_buffer_drain(cb)` | Reconnect buffer overflow     |

## Quick Usage [#quick-usage]

```cpp title="connect.cc"
kubemq::ClientOptions opts;
opts.set_address("localhost", 50000);
opts.set_client_id("my-client");

auto client_or = kubemq::Client::Create(opts);
if (!client_or.ok()) {
    std::cerr << "Failed: " << client_or.status().ToString() << "\n";
    return 1;
}
auto& client = *client_or;

auto ping_or = client->Ping();
if (ping_or.ok()) {
    std::cout << "Connected to " << ping_or->host << "\n";
}

client->Close();
```

## See Also [#see-also]

* [Connection Examples](/sdks/cpp/how-to/connection/)
* Concepts
* [C++ SDK Getting Started](/sdks/cpp)
