# Client

Canonical: https://docs.projectbabbage.com/docs/guides/messagebox/client

Guide for integrating and using the MessageBox Client to send, receive, and manage messages from a MessageBox Server.

## Overview
The **MessageBox Client** provides an interface for interacting with the MessageBox Server. It supports both real-time messaging via WebSocket and traditional HTTP requests. This guide covers how to initialize the client, join WebSocket rooms, send and receive live messages, and use HTTP as a fallback.

### Initialization
To begin, create an instance of the MessageBox Client and initialize the connection:
```ts
import { MessageBoxClient } from '@bsv/message-box-client'
import { WalletClient } from '@bsv/sdk'

const walletClient = new WalletClient('auto')
const messageBoxClient = new MessageBoxClient({ walletClient, enableLogging: false })

// Initialize the connection to fetch identity key and establish WebSocket
await messageBoxClient.initializeConnection()
```
**Note:** Logging is disabled by default. You can enable it by setting `enableLogging: true` when instantiating the client. This is useful for debugging.

The `initializeConnection()` method:

- Retrieves the client’s identity key via the `WalletClient`.

- Establishes an authenticated WebSocket connection with the `MessageBox Server`.

- Listens for events such as `connect` and `authenticationSuccess`, and handles errors.

________________________________________

### WebSocket Operations
**Joining a Room**
Before sending or receiving live messages, join a room associated with a specific message box:

```ts
await messageBoxClient.joinRoom('payment_inbox')
```
This method ensures that:

- The WebSocket connection is active.

- The client joins a room based on its identity key and the message box name.

- Duplicate joins are avoided by tracking joined rooms.

**Listening for Live Messages**
Set up a listener to receive messages in real time:

```ts
await messageBoxClient.listenForLiveMessages({
  messageBox: 'payment_inbox',
  onMessage: (message) => {
    console.log('Received message:', message)
  }
})
```
This registers an event listener on the WebSocket, so whenever a new message is sent to the joined room, your `onMessage` callback is executed.

**Sending Live Messages**
The `sendLiveMessage()` method attempts to send a message via WebSocket. If the WebSocket isn’t connected or the acknowledgment times out, it falls back to HTTP:

```ts
const response = await messageBoxClient.sendLiveMessage({
  recipient: '028d37b941208cd6b8a4c28288eda5f2f16c2b3ab0fcb6d13c18b47fe37b971fc1',
  messageBox: 'payment_inbox',
  body: { text: 'Hello, world!' }
})
```

Under the hood, this method:

- Joins the appropriate WebSocket room.

- Generates a unique message identifier using HMAC.

- Sends the message over WebSocket and listens for an acknowledgment.

- Falls back to sending the message via HTTP if needed.

________________________________________

### Leaving a Room and Disconnecting
When you no longer need to receive live messages, leave the room and disconnect the WebSocket:

```ts
await messageBoxClient.leaveRoom('payment_inbox')
await messageBoxClient.disconnectWebSocket()
```

________________________________________

### HTTP Fallback Methods
In cases where the WebSocket connection fails, the client supports HTTP methods for sending and managing messages.

**Sending a Message via HTTP**
If the WebSocket isn’t available, use the HTTP method:

```ts
const response = await messageBoxClient.sendMessage({
  recipient: '028d37b941208cd6b8a4c28288eda5f2f16c2b3ab0fcb6d13c18b47fe37b971fc1',
  messageBox: 'payment_inbox',
  body: { text: 'Hello via HTTP!' }
})
```

This method validates inputs, generates a unique message identifier, and sends a POST request to the MessageBox Server.

**Listing and Acknowledging Messages**
To list messages from the server:

```ts
const messages = await messageBoxClient.listMessages({ messageBox: 'payment_inbox' })
console.log('Messages:', messages)
```

And to acknowledge messages (removing them from the server):

```ts
await messageBoxClient.acknowledgeMessage({ messageIds: ['xyz123'] })
```

________________________________________

### Error Handling and Logging
Throughout all operations, the client uses logging to record events and errors. If issues arise—such as a missing identity key, failed authentication, or network errors—the client logs them and throws errors. Wrap your method calls in try-catch blocks to handle these exceptions gracefully.

________________________________________

### Summary
The MessageBox Client simplifies integration with the MessageBox Server by:

- Establishing secure, authenticated WebSocket connections.

- Allowing real-time message sending and receiving.

- Providing fallback HTTP methods for message operations.

- Managing WebSocket room memberships effectively.

By following this guide, developers can integrate the MessageBox Client into their applications for a seamless messaging experience.

________________________________________
