# Server.connected(attachingTo:_:)

- **Module:** Server
- **Package:** libtmux-swift
- **Language:** Swift
- **Kind:** method
- **Source:** https://github.com/libtmux/libtmux-swift/blob/f02a4668570e1cc5198c941413750e021f42c214/Sources/LibTmux/ControlMode.swift#L93
- **Page:** https://libtmux.org/reference/swift/server-connected(attachingto-_-)/

```
Server.connected(attachingTo:_:)(attachingTo: String, body: @escaping (Server, ControlSession) async throws -> Result) -> Result
```

Runs `body` with every command carried by one live connection instead of a new tmux process each time.

The server handed to `body` is this server: the same calls, the same
return types, the same errors. Only how the work reaches tmux changes.

```swift
let names = try await server.connected(attachingTo: "main") { server, _ in
    try await server.sessions().map(\.name)
}
```

A connection is a client, and tmux has no client that is attached to
nothing — a control client with no target runs tmux's default command
and creates a session. So the connection attaches to `session`, and that
is visible in what the server reports about itself: that session reads
as attached, and ``Server/clients()`` includes the connection. Nothing
else differs.

The connection is handed over too, because it can do one thing a
process cannot: report what changed without being asked. That capability
exists only here, and so does the value carrying it — there is no way to
write a `%output` reader against a server that has no connection.

The handed-out values do not keep the connection alive. Do not return
or store them; calls made after `body` ends fail because the process has
already been reaped.

- Parameters:
  - session: the session to attach to, which must already exist.
  - body: the work to run, given this server and the connection
    carrying it.
- Throws: ``TmuxError/connectionClosed`` if the connection ends before
  `body`, including when `body` detaches its own client.

## Raises

- `Result`
