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:
1import { MessageBoxClient } from '@bsv/message-box-client'
2import { WalletClient } from '@bsv/sdk'
3
4const walletClient = new WalletClient('auto')
5const messageBoxClient = new MessageBoxClient({ walletClient, enableLogging: false })
6
7// Initialize the connection to fetch identity key and establish WebSocket
8await 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
connectandauthenticationSuccess, and handles errors.
WebSocket Operations
Joining a Room Before sending or receiving live messages, join a room associated with a specific message box:
1await 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:
1await messageBoxClient.listenForLiveMessages({
2 messageBox: 'payment_inbox',
3 onMessage: (message) => {
4 console.log('Received message:', message)
5 }
6})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:
1const response = await messageBoxClient.sendLiveMessage({
2 recipient: '028d37b941208cd6b8a4c28288eda5f2f16c2b3ab0fcb6d13c18b47fe37b971fc1',
3 messageBox: 'payment_inbox',
4 body: { text: 'Hello, world!' }
5})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:
1await messageBoxClient.leaveRoom('payment_inbox')
2await 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:
1const response = await messageBoxClient.sendMessage({
2 recipient: '028d37b941208cd6b8a4c28288eda5f2f16c2b3ab0fcb6d13c18b47fe37b971fc1',
3 messageBox: 'payment_inbox',
4 body: { text: 'Hello via HTTP!' }
5})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:
1const messages = await messageBoxClient.listMessages({ messageBox: 'payment_inbox' })
2console.log('Messages:', messages)And to acknowledge messages (removing them from the server):
1await 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.
