# Connect (/sdks/ruby/tutorials/connect)



## Overview [#overview]

Every KubeMQ application starts the same way: open a connection to the broker and prove it actually works before building anything on top of it. This tutorial is that first lesson — create a client, give it a stable identity, and confirm connectivity with a health check, so the pattern is muscle memory before you move on to real messaging.

`KubeMQ::PubSubClient.new` (or `QueuesClient` / `CQClient`) is constructed with an `address` and a `client_id` — the ID tags this connection in broker logs, subscriptions, and management views, so pick something stable rather than a random string. `client.ping` verifies the round trip cheaply: it returns broker metadata (version, uptime) instead of just "no exception," proving the client is talking to a real broker rather than silently misconfigured. `client.close` releases the connection; wrap it in `ensure` so cleanup runs even if `ping` raises.

**Gotchas:** a successful construction doesn't always mean the broker is reachable — connection can happen lazily, so `ping` is the only reliable proof; reusing the same client ID across running instances causes routing confusion on the broker; and forgetting `close` (or an `ensure` block) in quick scripts is a common source of leaked connections under load.

## Prerequisites [#prerequisites]

* KubeMQ server running on `localhost:50000`
* Ruby SDK installed (`gem install kubemq`)

## Code [#code]

```ruby title="main.rb"
require 'kubemq'

address = ENV.fetch('KUBEMQ_ADDRESS', 'localhost:50000')

begin
  client = KubeMQ::PubSubClient.new(address: address, client_id: 'connect-example')
  info = client.ping
  puts "Minimal client connected. Server: #{info.version}"
  client.close

  client = KubeMQ::QueuesClient.new(address: address, client_id: 'connect-configured')
  info = client.ping
  puts "Configured client connected. Server: #{info.version}"
  client.close
rescue KubeMQ::Error => e
  puts "KubeMQ error: #{e.message}"
ensure
  puts 'Done'
end
```

## How It Works [#how-it-works]

* The SDK provides three client classes (`PubSubClient`, `QueuesClient`, `CQClient`) — each connects identically via keyword arguments.
* `ping` verifies connectivity and returns broker metadata including version and uptime.
* Review timeouts, channel names, and client IDs before running against shared environments.

## Related [#related]

* [Ruby SDK Reference](/sdks/ruby/reference)
* [Close](/sdks/ruby/how-to/connection/close)
* [Ping](/sdks/ruby/how-to/connection/ping)
