### Check Authentication Status Example Source: https://github.com/socketcluster/socketcluster-client/blob/master/_autodocs/api-reference/AGClientSocket.md An example showing how to retrieve the authentication token using `getAuthToken` and check for specific claims like `userId` to determine login status. ```javascript let token = socket.getAuthToken(); if (token && token.userId) { console.log('Logged in as user:', token.userId); } ``` -------------------------------- ### Install SocketCluster Client Source: https://github.com/socketcluster/socketcluster-client/blob/master/README.md Install the socketcluster-client package using npm. This is a prerequisite for using the client library. ```bash npm install socketcluster-client ``` -------------------------------- ### Receiver Stream Example Source: https://github.com/socketcluster/socketcluster-client/blob/master/_autodocs/api-reference/SocketClusterClient.md Example of setting up a receiver stream to listen for inbound 'transmit' messages from the server without expecting an acknowledgment. ```javascript for await (let data of socket.receiver('eventName')) { console.log('Received:', data); } ``` -------------------------------- ### Batch Transmission Example Source: https://github.com/socketcluster/socketcluster-client/blob/master/_autodocs/api-reference/AGClientSocket.md Demonstrates the usage of `startBatch`, `transmit`, and `flushBatch` to send multiple messages as a single batch. ```javascript socket.startBatch(); socket.transmit('msg1', data1); socket.transmit('msg2', data2); socket.transmit('msg3', data3); socket.flushBatch(); ``` -------------------------------- ### Backpressure Handling Example Source: https://github.com/socketcluster/socketcluster-client/blob/master/_autodocs/api-reference/AGTransport.md Demonstrates how to handle backpressure by checking the buffer threshold and waiting before sending more data. ```javascript if (transport.backpressure > threshold) { // Wait before sending more await new Promise(resolve => setTimeout(resolve, 100)); } ``` -------------------------------- ### Example Socket Creation with Options Source: https://github.com/socketcluster/socketcluster-client/blob/master/_autodocs/api-reference/Factory.md Demonstrates creating a socket instance with specific configuration options like hostname, port, secure, and autoConnect. ```javascript const socket = socketClusterClient.create({ hostname: 'localhost', port: 8000, secure: false, autoConnect: true }); ``` -------------------------------- ### Get All Consumers Across All Procedures Source: https://github.com/socketcluster/socketcluster-client/blob/master/_autodocs/api-reference/Streams.md Example of retrieving statistics for all consumers across all procedures using socket.getAllProceduresConsumerStatsList(). ```javascript const stats = socket.getAllProceduresConsumerStatsList() ``` -------------------------------- ### Managing Channels with AGChannel Source: https://github.com/socketcluster/socketcluster-client/blob/master/_autodocs/api-reference/AGChannel.md Demonstrates how to get a list of subscribed channels, check subscription status, unsubscribe from a channel, and get a channel instance without subscribing. ```javascript const socket = socketClusterClient.create({ hostname: 'localhost', port: 8000 }); // Get list of subscribed channels let channels = socket.subscriptions(); console.log('Subscribed to:', channels); // ['news', 'sports'] // Check if subscribed to a channel if (socket.isSubscribed('news')) { console.log('Already subscribed to news'); } // Unsubscribe through socket socket.unsubscribe('news'); // Get channel without subscribing let channel = socket.channel('sports'); // ... later ... channel.subscribe(); ``` -------------------------------- ### Install Development Dependencies Source: https://github.com/socketcluster/socketcluster-client/blob/master/README.md Install global and local development dependencies required for building the SocketCluster client. This includes tools like Gulp and Browserify. ```bash cd socketcluster-client npm install -g gulp gulp-cli browserify uglify-es npm install ``` -------------------------------- ### Listen to Channel Events Source: https://github.com/socketcluster/socketcluster-client/blob/master/_autodocs/api-reference/AGChannel.md Get an async iterable stream for specific channel events like 'subscribe', 'subscribeFail', 'unsubscribe', or 'subscribeStateChange'. This example listens for the 'subscribe' event. ```javascript (async () => { let channel = socket.subscribe('news'); // Listen for subscription success for await (let event of channel.listener('subscribe')) { console.log('Subscribed:', event); break; // Usually only fires once } })(); ``` -------------------------------- ### Log Out Example Source: https://github.com/socketcluster/socketcluster-client/blob/master/_autodocs/api-reference/AGClientSocket.md An example demonstrating how to use `deauthenticate` to log out the user and confirm the action with a console message. ```javascript await socket.deauthenticate(); console.log('Logged out'); ``` -------------------------------- ### Real-World Connection and Subscription Workflow Source: https://github.com/socketcluster/socketcluster-client/blob/master/_autodocs/api-reference/EventHandling.md A comprehensive example demonstrating the complete workflow for establishing a SocketCluster connection, handling authentication, subscribing to a channel, and publishing messages. ```javascript const socketClusterClient = require('socketcluster-client'); (async () => { // Create socket const socket = socketClusterClient.create({ hostname: 'localhost', port: 8000, autoConnect: true }); // Wait for connection for await (let event of socket.listener('connect')) { console.log('✓ Connected to server'); break; } // Handle errors (async () => { for await (let error of socket.listener('error')) { console.error('✗ Error:', error.message); } })(); // Try to authenticate try { let result = await socket.invoke('login', { username: 'alice', password: 'secret' }); console.log('✓ Authenticated'); } catch (err) { console.error('✗ Authentication failed:', err.message); return; } // Subscribe to channel let channel = socket.subscribe('messages'); for await (let event of channel.listener('subscribe')) { console.log('✓ Subscribed to messages channel'); break; } // Start consuming messages (async () => { for await (let message of channel) { console.log('📨 Message:', message); } })(); // Publish a message channel.transmitPublish({ username: 'alice', text: 'Hello everyone!' }); })(); ``` -------------------------------- ### Basic Socket Connection Example Source: https://github.com/socketcluster/socketcluster-client/blob/master/_autodocs/api-reference/Factory.md Establishes a basic connection to a SocketCluster server using the create function and logs a message upon successful connection. ```javascript const socketClusterClient = require('socketcluster-client'); const socket = socketClusterClient.create({ hostname: 'example.com', port: 8000, secure: true }); socket.listener('connect').once().then(() => { console.log('Connected to server'); }); ``` -------------------------------- ### Wait for Connection and Channel Subscription using once() Source: https://github.com/socketcluster/socketcluster-client/blob/master/_autodocs/api-reference/EventHandling.md This example demonstrates using the 'once()' method to wait for a 'connect' event and then subsequently wait for a channel 'subscribe' event. ```javascript // Wait for connection let connectEvent = await socket.listener('connect').once(); console.log('Connected!'); // Wait for channel subscription let subEvent = await socket.subscribe('news').listener('subscribe').once(); console.log('Subscribed to news'); ``` -------------------------------- ### Asynchronously Listen for Channel Subscriptions Source: https://github.com/socketcluster/socketcluster-client/blob/master/_autodocs/api-reference/EventHandling.md This example demonstrates how to asynchronously listen for channel subscription events and log the subscribed channel name. ```javascript (async () => { for await (let {channel} of socket.listener('subscribe')) { console.log('Successfully subscribed to:', channel); } })(); ``` -------------------------------- ### Get All Procedure Consumer Statistics Source: https://github.com/socketcluster/socketcluster-client/blob/master/_autodocs/api-reference/Streams.md Example of retrieving statistics for all consumers on a specified procedure using socket.getProcedureConsumerStatsList(). ```javascript const stats = socket.getProcedureConsumerStatsList(procedureName) ``` -------------------------------- ### Procedure Stream Example Source: https://github.com/socketcluster/socketcluster-client/blob/master/_autodocs/api-reference/SocketClusterClient.md Example of handling inbound RPC calls from the server. The client listens for procedure calls and responds using `rpc.end()`. ```javascript for await (let rpc of socket.procedure('methodName')) { rpc.end(responseValue); } ``` -------------------------------- ### SocketCluster Client Constructor Options Example Source: https://github.com/socketcluster/socketcluster-client/blob/master/_autodocs/configuration.md Demonstrates passing configuration options to the socketClusterClient.create() function. These options control various aspects of the client's behavior, such as connection timeouts, reconnection logic, and data handling. ```javascript const socket = socketClusterClient.create({ hostname: 'example.com', port: 8080, secure: true, path: '/custom-path/', autoConnect: false, autoReconnect: { initialDelay: 5000, randomness: 2000, multiplier: 1.2, maxDelay: 30000 }, connectTimeout: 15000, ackTimeout: 5000, wsOptions: { rejectUnauthorized: false }, query: { authToken: 'your-auth-token' } }); ``` -------------------------------- ### Get All Consumers Across All Receivers Source: https://github.com/socketcluster/socketcluster-client/blob/master/_autodocs/api-reference/Streams.md Example of retrieving statistics for all consumers across all receivers using socket.getAllReceiversConsumerStatsList(). ```javascript const stats = socket.getAllReceiversConsumerStatsList() ``` -------------------------------- ### Validating Host Format Source: https://github.com/socketcluster/socketcluster-client/blob/master/_autodocs/api-reference/Factory.md Demonstrates the correct usage of the 'host' option with both hostname and port, and shows an invalid example missing the port. ```javascript // Valid socketClusterClient.create({ host: 'localhost:8000' }); // Invalid - missing port socketClusterClient.create({ host: 'localhost' }); // Error ``` -------------------------------- ### Invoke RPC Example Source: https://github.com/socketcluster/socketcluster-client/blob/master/_autodocs/api-reference/SocketClusterClient.md Example of invoking a remote procedure call (RPC) on the server and waiting for a response. Includes basic error handling for RPC failures. ```javascript let response = await socket.invoke('procedureName', { params }); ``` -------------------------------- ### Listen for Connect Event with Once Source: https://github.com/socketcluster/socketcluster-client/blob/master/_autodocs/api-reference/EventHandling.md Asynchronously waits for a single 'connect' event using a listener. This is useful for initial setup after a connection is established. ```javascript (async () => { let listener = socket.listener('connect'); while (true) { try { let event = await listener.once(); console.log('Connected'); } catch (err) { console.error('Error:', err); break; } } })(); ``` -------------------------------- ### Run SocketCluster Client Tests Source: https://github.com/socketcluster/socketcluster-client/blob/master/README.md Instructions for setting up and running integration tests for the SocketCluster client. This involves cloning the repository, installing dependencies, and executing the test suite. ```bash # Clone this repo: git clone git@github.com:SocketCluster/socketcluster-client.git # Navigate to project directory: cd socketcluster-client # Install all dependencies: npm install # Run the tests: npm test ``` -------------------------------- ### Custom Authentication Engine Implementation Source: https://github.com/socketcluster/socketcluster-client/blob/master/_autodocs/api-reference/SocketClusterClient.md Shows how to create a custom authentication engine by extending the base class. This example implements token saving, loading, and removal using a database. The custom engine is then passed to the socket client during creation. ```javascript class DatabaseAuthEngine { async saveToken(name, token, options) { await db.tokens.save(name, token); } async loadToken(name) { return await db.tokens.get(name); } async removeToken(name) { return await db.tokens.delete(name); } } const socket = socketClusterClient.create({ authEngine: new DatabaseAuthEngine() }); ``` -------------------------------- ### Factory: Create Socket Instance Source: https://github.com/socketcluster/socketcluster-client/blob/master/_autodocs/README.md Use the `create` method from the factory to instantiate a new socket client. This is the recommended way to start using the client. ```APIDOC ## Factory.create ### Description Creates a new socket cluster client instance with the specified options. ### Method Factory method ### Parameters #### Options - **options** (object) - Optional - Configuration options for the socket client. See `configuration.md` for details. ### Request Example ```javascript const socketClusterClient = require('socketcluster-client'); const socket = socketClusterClient.create({ hostname: 'localhost', port: 8000, connectTimeout: 10000 }); ``` ### Response #### Success Response - **socket** (AGClientSocket) - An instance of the AGClientSocket class. ``` -------------------------------- ### Start Message Batching Source: https://github.com/socketcluster/socketcluster-client/blob/master/_autodocs/api-reference/AGTransport.md Call startBatch() to begin buffering outbound messages. This allows for efficient sending of multiple messages at once. ```javascript transport.startBatch() ``` -------------------------------- ### Consuming a Procedure (e.g., 'divide') Source: https://github.com/socketcluster/socketcluster-client/blob/master/_autodocs/api-reference/Streams.md This example demonstrates how to consume a procedure named 'divide'. It iterates over incoming RPCs, performs a division, and sends the result back using `rpc.end()`. It also includes error handling for division by zero, sending the error back using `rpc.error()`. ```APIDOC ## Consume Procedure 'divide' ### Description Consumes a remote procedure named 'divide'. It expects input data with properties 'a' and 'b'. If 'b' is zero, it throws an error. Otherwise, it calculates 'a' / 'b' and sends the result back to the server. ### Method `socket.procedure('divide')` ### Parameters None directly on the `procedure` method, but the data passed to the procedure is expected to have 'a' and 'b' properties. ### Request Example ```javascript (async () => { for await (let rpc of socket.procedure('divide')) { try { if (rpc.data.b === 0) { throw new Error('Cannot divide by zero'); } let result = rpc.data.a / rpc.data.b; rpc.end(result); } catch (err) { // Send error back to server rpc.error(err); } } })(); ``` ### Response Methods - `rpc.end(value)`: Sends a successful response. - `rpc.error(error, backError)`: Sends an error response. ``` -------------------------------- ### Transmit Message Example Source: https://github.com/socketcluster/socketcluster-client/blob/master/_autodocs/api-reference/SocketClusterClient.md Example of sending a 'fire-and-forget' message to the server using the transmit method. No acknowledgment is expected from the server. ```javascript socket.transmit('eventName', { payload }); ``` -------------------------------- ### Listen for Subscription Success Event Source: https://github.com/socketcluster/socketcluster-client/blob/master/_autodocs/api-reference/AGChannel.md Listen for the 'subscribe' event, which is emitted when the server confirms the subscription. This example breaks after the first event. ```javascript (async () => { let channel = socket.subscribe('news'); for await (let event of channel.listener('subscribe')) { console.log('Successfully subscribed'); // event.subscriptionOptions may contain server-provided data break; } })(); ``` -------------------------------- ### Handle Socket Authentication Source: https://github.com/socketcluster/socketcluster-client/blob/master/_autodocs/api-reference/AGClientSocket.md An example demonstrating how to use `authenticate` within a try-catch block to handle potential authentication errors. Ensure you have a valid `jwtToken`. ```javascript try { await socket.authenticate(jwtToken); console.log('Authenticated successfully'); } catch (err) { console.error('Authentication failed:', err.message); } ``` -------------------------------- ### Retry Channel Subscription on Failure Source: https://github.com/socketcluster/socketcluster-client/blob/master/_autodocs/api-reference/EventHandling.md This example demonstrates how to retry subscribing to a channel after a 'subscribeFail' event. It waits for a delay before attempting to resubscribe. ```javascript (async () => { let channel = socket.subscribe('admin'); for await (let error of channel.listener('subscribeFail')) { console.error('Subscription failed:', error.message); // Retry after delay await new Promise(resolve => setTimeout(resolve, 1000)); channel.subscribe(); } })(); ``` -------------------------------- ### version Source: https://github.com/socketcluster/socketcluster-client/blob/master/_autodocs/api-reference/Factory.md Get the version string of the socketcluster-client package. ```APIDOC ## version ### Description Provides the version string of the socketcluster-client package. ### Method Property access ### Endpoint N/A (Module property) ### Parameters None ### Request Example ```javascript console.log(socketClusterClient.version); ``` ### Response #### Success Response (200) * **version** (string) - The version string of the package (e.g., '20.0.1') #### Response Example '20.0.1' ``` -------------------------------- ### Connect with Timeout Source: https://github.com/socketcluster/socketcluster-client/blob/master/_autodocs/README.md Establish a connection to SocketCluster with a specified connection timeout. This example demonstrates waiting for the 'connect' event and handling connection failures. ```javascript const socket = socketClusterClient.create({ hostname: 'localhost', port: 8000, connectTimeout: 10000 }); try { await socket.listener('connect').once(); console.log('Connected'); } catch (err) { console.error('Connection failed'); } ``` -------------------------------- ### Server-Initiated Data Sync Example Source: https://github.com/socketcluster/socketcluster-client/blob/master/_autodocs/api-reference/Streams.md Client-side code to handle data synchronization requests initiated by the server. The client retrieves local data and sends it back upon request. ```javascript // Client: Handle sync requests from server (async () => { for await (let request of socket.procedure('sync')) { let data = await getLocalData(); request.end(data); } })(); // Server: // let clientData = await socket.invoke('sync', {}); ``` -------------------------------- ### Server Push Notifications Example Source: https://github.com/socketcluster/socketcluster-client/blob/master/_autodocs/api-reference/Streams.md Client-side code to listen for server push notifications on the 'notify' stream. Assumes a server-side transmission of notifications. ```javascript // Client: Listen for notifications (async () => { for await (let notification of socket.receiver('notify')) { showNotification(notification.title, notification.message); } })(); // Server: // socket.transmit('notify', { title: 'Alert', message: '...' }); ``` -------------------------------- ### Asynchronously Listen for Channel Subscription State Changes Source: https://github.com/socketcluster/socketcluster-client/blob/master/_autodocs/api-reference/EventHandling.md This example asynchronously listens for channel subscription state changes and logs messages indicating whether the channel is now subscribed or unsubscribed. ```javascript (async () => { for await (let event of socket.listener('subscribeStateChange')) { if (event.newChannelState === 'subscribed') { console.log(`${event.channel} is now subscribed`); } else if (event.newChannelState === 'unsubscribed') { console.log(`${event.channel} is now unsubscribed`); } } })(); ``` -------------------------------- ### localStorage Availability Detection Example Source: https://github.com/socketcluster/socketcluster-client/blob/master/_autodocs/api-reference/AuthEngine.md Demonstrates how AuthEngine detects localStorage availability. In private browsing mode, isLocalStorageEnabled will be false, and tokens will be stored in-memory. ```javascript // Browser in private mode: const authEngine = new AuthEngine(); console.log(authEngine.isLocalStorageEnabled); // false // Tokens stored in-memory, lost on page refresh ``` -------------------------------- ### Handle Incoming RPC Calls Source: https://github.com/socketcluster/socketcluster-client/blob/master/_autodocs/api-reference/AGClientSocket.md An example demonstrating how to consume RPC requests from a procedure stream and send back responses. Ensure to close or end each RPC after processing. ```javascript (async () => { for await (let rpc of socket.procedure('getData')) { rpc.end({ result: computeData(rpc.data) }); } })(); ``` -------------------------------- ### Get All Receiver Consumer Statistics Source: https://github.com/socketcluster/socketcluster-client/blob/master/_autodocs/api-reference/Streams.md Example of retrieving statistics for all consumers (listeners) on a specified receiver using socket.getReceiverConsumerStatsList(). ```javascript const stats = socket.getReceiverConsumerStatsList(receiverName) ``` -------------------------------- ### Default Token Storage Key Format Source: https://github.com/socketcluster/socketcluster-client/blob/master/_autodocs/api-reference/AuthEngine.md Illustrates the default format for token storage keys, which are auto-generated based on the connection URI. Shows examples for localhost, secure connections, and custom host options. ```javascript // For localhost:8000 'socketcluster.authToken.localhost:8000' // For secure connection to example.com:443 'socketcluster.authToken.example.com:443' // For custom host option 'socketcluster.authToken.custom.host:port' ``` -------------------------------- ### Get Specific Procedure Consumer Statistics Source: https://github.com/socketcluster/socketcluster-client/blob/master/_autodocs/api-reference/Streams.md Example of retrieving statistics for a single, specific procedure consumer using its ID with socket.getProcedureConsumerStats(). ```javascript const stats = socket.getProcedureConsumerStats(consumerId) ``` -------------------------------- ### Consuming a Procedure (e.g., 'processData') Source: https://github.com/socketcluster/socketcluster-client/blob/master/_autodocs/api-reference/Streams.md This example shows how to consume a procedure named 'processData'. It validates the incoming data for a required 'id' field. If valid, it fetches a record using the 'id' and sends the record back using `rpc.end()`. If the 'id' is missing, it sends an error back using `rpc.error()`. ```APIDOC ## Consume Procedure 'processData' ### Description Consumes a remote procedure named 'processData'. It expects input data with an 'id' property. It uses this 'id' to fetch a record from a database and sends the record back to the server. ### Method `socket.procedure('processData')` ### Parameters - **data** (object) - Required - The data payload for the procedure, expected to contain an `id` property. - **id** (string) - Required - The identifier for the record to process. ### Request Example ```javascript (async () => { for await (let rpc of socket.procedure('processData')) { // Validate input if (!rpc.data || !rpc.data.id) { rpc.error(new Error('Missing required field: id')); continue; } // Process let record = await database.findById(rpc.data.id); rpc.end(record); } })(); ``` ### Response Methods - `rpc.end(value)`: Sends the fetched record back to the server. - `rpc.error(error)`: Sends an error if the 'id' is missing. ``` -------------------------------- ### Listen for Subscription Failure Event Source: https://github.com/socketcluster/socketcluster-client/blob/master/_autodocs/api-reference/AGChannel.md Listen for the 'subscribeFail' event, emitted when subscription fails due to reasons like permission denial or authentication requirements. This example handles the error and breaks. ```javascript (async () => { let channel = socket.subscribe('admin', { waitForAuth: true }); for await (let error of channel.listener('subscribeFail')) { console.error('Subscription failed:', error.message); // Handle subscription failure break; } })(); ``` -------------------------------- ### Get Specific Receiver Consumer Statistics Source: https://github.com/socketcluster/socketcluster-client/blob/master/_autodocs/api-reference/Streams.md Example of retrieving statistics for a single, specific consumer on a receiver using its ID with socket.getReceiverConsumerStats(). ```javascript const stats = socket.getReceiverConsumerStats(consumerId) ``` -------------------------------- ### Authentication Engine Instantiation Source: https://github.com/socketcluster/socketcluster-client/blob/master/_autodocs/README.md Create an instance of the `AuthEngine` for managing authentication tokens. ```javascript new AuthEngine() ``` -------------------------------- ### Message Frame Format Example Source: https://github.com/socketcluster/socketcluster-client/blob/master/_autodocs/api-reference/AGTransport.md Illustrates the structure of messages sent over the WebSocket, including event, data, call ID, and response ID. ```json { event: 'eventName', data: { ... }, cid: 1, rid: 1 } ``` -------------------------------- ### startBatch() Source: https://github.com/socketcluster/socketcluster-client/blob/master/_autodocs/api-reference/AGTransport.md Begins buffering outbound messages to be sent together. ```APIDOC ## startBatch() ### Description Begins buffering outbound messages to be sent together. ### Method POST ### Endpoint `/batch/start` ### Returns #### Success Response (200) - **status** (string) - Indicates batching has started. ``` -------------------------------- ### In-Memory Storage Fallback Example Source: https://github.com/socketcluster/socketcluster-client/blob/master/_autodocs/api-reference/AuthEngine.md Illustrates the in-memory storage behavior when localStorage is not available. Tokens are stored in an internal object and persist only during the current page session. ```javascript // Example of in-memory storage behavior: await authEngine.saveToken('token1', 'abc123'); await authEngine.saveToken('token2', 'def456'); // Memory persists during page session: let token1 = await authEngine.loadToken('token1'); // 'abc123' // But is lost on page refresh or new instance: const newEngine = new AuthEngine(); let token1Again = await newEngine.loadToken('token1'); // null ``` -------------------------------- ### Handling 'connect' Socket Event Source: https://github.com/socketcluster/socketcluster-client/blob/master/_autodocs/api-reference/EventHandling.md Listen for the 'connect' event, emitted upon successful connection. The event object contains connection metadata. This example logs the socket ID and server information. ```javascript (async () => { for await (let event of socket.listener('connect')) { console.log('Connected with ID:', socket.id); console.log('Server info:', event); break; // Usually handle just once } })(); ``` -------------------------------- ### Channel Subscription and Usage Source: https://github.com/socketcluster/socketcluster-client/blob/master/_autodocs/api-reference/SocketClusterClient.md Demonstrates how to subscribe to a channel, consume messages from it using async iteration, publish messages to the channel, and optionally use invokePublish for confirmed publishes. ```javascript // Subscribe to channel let channel = socket.subscribe('channelName'); // Consume messages for await (let message of channel) { // Process message } // Publish to channel channel.transmitPublish({ data }); // Or with confirmation: await channel.invokePublish({ data }); ``` -------------------------------- ### Get a Single Message from a Receiver Stream Source: https://github.com/socketcluster/socketcluster-client/blob/master/_autodocs/api-reference/Streams.md To get only the first message from a receiver stream, you can use the `once()` method on the stream. The stream will continue to be active for subsequent messages. ```javascript (async () => { let stream = socket.receiver('announcement'); let firstMessage = await stream.once(); console.log('Got announcement:', firstMessage); // Continues waiting for more after once() })(); ``` -------------------------------- ### Send Error Response using rpc.error() Source: https://github.com/socketcluster/socketcluster-client/blob/master/_autodocs/api-reference/Streams.md Illustrates how to send an error response to the server using rpc.error(). The example also shows how the client would receive this error. ```javascript // Send error to server rpc.error(new Error('Processing failed')); // Client receives this as thrown error: // try { // let result = await socket.invoke('myProc', data); // } catch (err) { // // err.message === 'Processing failed' // // err.backError === true (came from server) // } ``` -------------------------------- ### Connect with New Options Source: https://github.com/socketcluster/socketcluster-client/blob/master/_autodocs/api-reference/AGClientSocket.md Establish or re-establish a connection to the server using potentially new configuration options. If already connected, it disconnects first. ```javascript // Connect with new options socket.connect({ hostname: 'newserver.com', port: 9000 }); ``` -------------------------------- ### getReceiverConsumerBackpressure Source: https://github.com/socketcluster/socketcluster-client/blob/master/_autodocs/api-reference/Streams.md Get the backpressure for a specific consumer within a receiver. ```APIDOC ## getReceiverConsumerBackpressure(consumerId) ### Description Get backpressure for a specific consumer. This indicates the number of messages waiting to be processed by this individual consumer. ### Method Not specified (assumed to be a client-side method call) ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```javascript const backpressure = socket.getReceiverConsumerBackpressure(consumerId) ``` ### Response #### Success Response - **backpressure** (number) - Consumer backpressure #### Response Example ```javascript 50 ``` ``` -------------------------------- ### SocketCluster Client Configuration Source: https://github.com/socketcluster/socketcluster-client/blob/master/_autodocs/api-reference/SocketClusterClient.md Shows how to create a SocketCluster client instance with various configuration options, including connection details, timeouts, and custom engines. ```javascript const socket = socketClusterClient.create({ hostname: 'localhost', // Server hostname port: 8000, // Server port secure: false, // Use WSS instead of WS autoConnect: true, // Connect automatically autoReconnect: true, // Auto-reconnect on disconnect connectTimeout: 20000, // Connection timeout (ms) ackTimeout: 10000, // RPC timeout (ms) path: '/socketcluster/', // WebSocket path query: { token: 'xyz' }, // Query parameters authEngine: customAuthEngine, // Custom token storage codecEngine: customCodec // Custom message encoding }); ``` -------------------------------- ### Get Channel Name Source: https://github.com/socketcluster/socketcluster-client/blob/master/_autodocs/api-reference/AGChannel.md Access the name of the subscribed channel. ```javascript let channel = socket.subscribe('news'); console.log(channel.name); ``` -------------------------------- ### Instantiate AuthEngine Source: https://github.com/socketcluster/socketcluster-client/blob/master/_autodocs/api-reference/AuthEngine.md Creates a new AuthEngine instance. It automatically detects localStorage availability and falls back to in-memory storage if needed. No parameters are required. ```javascript const authEngine = new AuthEngine() ``` -------------------------------- ### getAllReceiversBackpressure Source: https://github.com/socketcluster/socketcluster-client/blob/master/_autodocs/api-reference/Streams.md Get the total backpressure across all receivers managed by the client. ```APIDOC ## getAllReceiversBackpressure() ### Description Get total backpressure across all receivers. This provides an aggregated view of all pending messages across the client's receivers. ### Method Not specified (assumed to be a client-side method call) ### Endpoint N/A ### Parameters N/A ### Request Example ```javascript const backpressure = socket.getAllReceiversBackpressure() ``` ### Response #### Success Response - **backpressure** (number) - Total backpressure across all receivers #### Response Example ```javascript 1500 ``` ``` -------------------------------- ### create(options) Source: https://github.com/socketcluster/socketcluster-client/blob/master/_autodocs/api-reference/Factory.md Creates a new AGClientSocket instance with the provided configuration options. This is the recommended way to instantiate a socket, as it handles default settings and option validation. ```APIDOC ## create(options) ### Description Create a new AGClientSocket instance. ### Method Factory function ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **options** (AGClientSocketOptions) - Optional - Socket configuration options ### Request Example ```javascript const socket = socketClusterClient.create({ hostname: 'localhost', port: 8000, secure: false, autoConnect: true }); ``` ### Response #### Success Response (200) * **socket** (AGClientSocket) - New socket instance #### Response Example (No specific example provided, returns an AGClientSocket instance) ### Throws * **InvalidArgumentsError** - If configuration options are invalid ``` -------------------------------- ### Get Channel State Source: https://github.com/socketcluster/socketcluster-client/blob/master/_autodocs/api-reference/AGChannel.md Retrieve the current subscription state of the channel. ```javascript let channel = socket.subscribe('news'); console.log(channel.state); ``` -------------------------------- ### getReceiverBackpressure Source: https://github.com/socketcluster/socketcluster-client/blob/master/_autodocs/api-reference/Streams.md Get the total backpressure for a specific receiver, which is the sum of backpressure from all its consumers. ```APIDOC ## getReceiverBackpressure(receiverName) ### Description Get backpressure for a specific receiver. This method sums the backpressure of all consumers associated with the given receiver. ### Method Not specified (assumed to be a client-side method call) ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```javascript const backpressure = socket.getReceiverBackpressure(receiverName) ``` ### Response #### Success Response - **backpressure** (number) - Total backpressure (sum of all consumers for the receiver) #### Response Example ```javascript 150 ``` ``` -------------------------------- ### Socket Connection with Error Handling Source: https://github.com/socketcluster/socketcluster-client/blob/master/_autodocs/api-reference/Factory.md Demonstrates setting up listeners for 'error' and 'connectAbort' events to handle connection failures and socket errors gracefully. ```javascript const socket = socketClusterClient.create({ hostname: 'localhost', port: 8000 }); socket.listener('error').on((err) => { console.error('Socket error:', err.message); }); socket.listener('connectAbort').on((err) => { console.error('Connection failed:', err.reason); }); ``` -------------------------------- ### getProcedureBackpressure Source: https://github.com/socketcluster/socketcluster-client/blob/master/_autodocs/api-reference/Streams.md Get the backpressure for a specific procedure. This is useful for monitoring the load on procedures that handle requests. ```APIDOC ## getProcedureBackpressure(procedureName) ### Description Get backpressure for a specific procedure. This indicates the number of pending requests or messages for the given procedure. ### Method Not specified (assumed to be a client-side method call) ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```javascript const backpressure = socket.getProcedureBackpressure(procedureName) ``` ### Response #### Success Response - **backpressure** (number) - Total backpressure for the procedure #### Response Example ```javascript 75 ``` ``` -------------------------------- ### Get Bytes Received Source: https://github.com/socketcluster/socketcluster-client/blob/master/_autodocs/README.md Retrieve the total number of bytes received by the socket since its creation. ```javascript socket.getBytesReceived() ``` -------------------------------- ### Get Total Bytes Received Source: https://github.com/socketcluster/socketcluster-client/blob/master/_autodocs/api-reference/AGTransport.md Retrieve the cumulative number of bytes received over the current connection. ```javascript const bytes = transport.getBytesReceived() ``` -------------------------------- ### Get Channel Listener Source: https://github.com/socketcluster/socketcluster-client/blob/master/_autodocs/api-reference/EventHandling.md Retrieve an event listener for a specific channel. This is used to subscribe to channel-specific events. ```javascript channel.listener('subscribe') channel.listener('subscribeFail') channel.listener('unsubscribe') channel.listener('subscribeStateChange') ``` -------------------------------- ### Create SocketCluster Client Source: https://github.com/socketcluster/socketcluster-client/blob/master/_autodocs/api-reference/AGClientSocket.md Use the recommended factory function to create a socket instance. This simplifies the instantiation process. ```javascript const socket = socketClusterClient.create({ hostname: 'localhost', port: 8000 }); ``` -------------------------------- ### Get Backpressure Source: https://github.com/socketcluster/socketcluster-client/blob/master/_autodocs/api-reference/AGClientSocket.md Retrieve the current backpressure level across all streams. This indicates the amount of data waiting to be sent. ```javascript socket.getBackpressure(); ``` -------------------------------- ### Getting First Event Only Source: https://github.com/socketcluster/socketcluster-client/blob/master/_autodocs/api-reference/EventHandling.md Obtain only the first event from a listener. The listener is no longer active after the first event is received. ```javascript (async () => { let event = await socket.listener('connect').once(); console.log('Got first connect event'); // Just got first event, not listening anymore })(); ``` -------------------------------- ### Custom Codec Engine Implementation Source: https://github.com/socketcluster/socketcluster-client/blob/master/_autodocs/api-reference/SocketClusterClient.md Illustrates how to implement a custom codec engine using a library like msgpack5. The custom codec must provide `encode` and `decode` methods. This engine is then provided to the socket client configuration. ```javascript const msgpack = require('msgpack5')(); const customCodec = { encode: (obj) => msgpack.encode(obj), decode: (buf) => msgpack.decode(buf) }; const socket = socketClusterClient.create({ codecEngine: customCodec }); ``` -------------------------------- ### Multiple Socket Client Instances Source: https://github.com/socketcluster/socketcluster-client/blob/master/_autodocs/api-reference/SocketClusterClient.md Demonstrates how to create and manage multiple independent SocketCluster client instances, connecting to different servers. Each socket can be invoked independently. ```javascript // Connect to different servers const socket1 = socketClusterClient.create({ hostname: 'api.example.com', port: 8000 }); const socket2 = socketClusterClient.create({ hostname: 'realtime.example.com', port: 8001 }); // Use independently await socket1.invoke('method1', {}); await socket2.invoke('method2', {}); ``` -------------------------------- ### Get Socket Backpressure Source: https://github.com/socketcluster/socketcluster-client/blob/master/_autodocs/README.md Retrieve the current backpressure value for the socket, indicating the amount of data waiting to be sent. ```javascript socket.getBackpressure() ``` -------------------------------- ### Socket Class: Direct Instantiation Source: https://github.com/socketcluster/socketcluster-client/blob/master/_autodocs/README.md Instantiate `AGClientSocket` directly if you need more control or are importing specific classes. ```APIDOC ## AGClientSocket Constructor ### Description Initializes a new `AGClientSocket` instance. This is typically used when importing the class directly. ### Method Constructor ### Parameters #### Options - **options** (object) - Optional - Configuration options for the socket client. See `configuration.md` for details. ### Request Example ```javascript const { AGClientSocket } = require('socketcluster-client'); const socket = new AGClientSocket({ hostname: 'localhost', port: 8000 }); ``` ### Response #### Success Response - **socket** (AGClientSocket) - An instance of the AGClientSocket class. ``` -------------------------------- ### Get Event Listener Source: https://github.com/socketcluster/socketcluster-client/blob/master/_autodocs/README.md Obtain a listener object for a specific event on the socket. This allows for attaching event handlers. ```javascript socket.listener(eventName) ``` -------------------------------- ### Node.js Connection Options Source: https://github.com/socketcluster/socketcluster-client/blob/master/_autodocs/api-reference/Factory.md Configure connection details for Node.js, including hostname, port, security, and WebSocket options. Use `wsOptions` to pass Node.js specific WebSocket configurations. ```javascript const socket = socketClusterClient.create({ hostname: 'example.com', port: 8000, secure: true, wsOptions: { rejectUnauthorized: false // Allow self-signed certs in development } }); ``` -------------------------------- ### Get List of Subscribed Channels Source: https://github.com/socketcluster/socketcluster-client/blob/master/_autodocs/api-reference/AGClientSocket.md Retrieve an array of all channels you are currently subscribed to. Optionally include pending subscriptions in the list. ```javascript socket.subscriptions(includePending) ``` ```javascript let channels = socket.subscriptions(); console.log('Subscribed to:', channels); // ['news', 'updates'] ``` -------------------------------- ### Get Procedure Backpressure Source: https://github.com/socketcluster/socketcluster-client/blob/master/_autodocs/api-reference/Streams.md Retrieves the total backpressure for a specific procedure. Monitor this to understand the load on remote procedure calls. ```javascript const backpressure = socket.getProcedureBackpressure(procedureName) ``` -------------------------------- ### AuthEngine: Token Management Source: https://github.com/socketcluster/socketcluster-client/blob/master/_autodocs/README.md Instantiate `AuthEngine` for managing authentication tokens. ```APIDOC ## AuthEngine Constructor ### Description Initializes a new `AuthEngine` instance for managing authentication tokens. ### Method Constructor ### Request Example ```javascript const { AuthEngine } = require('socketcluster-client'); const authEngine = new AuthEngine(); ``` ### Response #### Success Response - **authEngine** (AuthEngine) - An instance of the AuthEngine class. ``` -------------------------------- ### Get Socket State Source: https://github.com/socketcluster/socketcluster-client/blob/master/_autodocs/README.md Retrieve the current connection state of the socket. Possible states include 'connecting', 'open', 'closed'. ```javascript socket.getState() ``` -------------------------------- ### AuthEngine Constructor Source: https://github.com/socketcluster/socketcluster-client/blob/master/_autodocs/api-reference/AuthEngine.md Creates a new AuthEngine instance. It automatically detects localStorage availability and falls back to in-memory storage if localStorage is not available or disabled. ```APIDOC ## AuthEngine() ### Description Initializes a new AuthEngine instance. This engine is designed to manage authentication tokens, prioritizing browser localStorage for persistence and providing an in-memory fallback for scenarios where localStorage is unavailable (e.g., private browsing). ### Parameters None ### Example ```javascript import { AuthEngine } from 'socketcluster-client'; const authEngine = new AuthEngine(); ``` ``` -------------------------------- ### Get Channel Event Listener Source: https://github.com/socketcluster/socketcluster-client/blob/master/_autodocs/README.md Obtain a listener object for a specific event on a channel. This allows for handling channel-specific events. ```javascript channel.listener(eventName) ``` -------------------------------- ### Get Channel Instance Source: https://github.com/socketcluster/socketcluster-client/blob/master/_autodocs/README.md Retrieve an instance of a channel by its name, without immediately subscribing. This allows for further operations on the channel object. ```javascript let channel = socket.channel(channelName) ``` -------------------------------- ### new AGClientSocket(options) Source: https://github.com/socketcluster/socketcluster-client/blob/master/_autodocs/api-reference/Factory.md Directly instantiate the AGClientSocket class for advanced use cases, providing configuration options to the constructor. ```APIDOC ## new AGClientSocket(options) ### Description Directly access the socket class for advanced use cases and instantiate it with provided options. ### Method Constructor ### Endpoint N/A (Class constructor) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **options** (AGClientSocketOptions) - Optional - Socket configuration options ### Request Example ```javascript const { AGClientSocket } = require('socketcluster-client'); const socket = new AGClientSocket(options); ``` ### Response #### Success Response (200) * **socket** (AGClientSocket) - New socket instance #### Response Example (No specific example provided, returns an AGClientSocket instance) ``` -------------------------------- ### Basic SocketCluster Client Usage Source: https://github.com/socketcluster/socketcluster-client/blob/master/_autodocs/api-reference/SocketClusterClient.md Demonstrates basic usage of the SocketCluster client, including creating a socket connection, waiting for connection, sending a fire-and-forget message, invoking an RPC and handling its response, and subscribing to a channel to receive messages. ```javascript const socketClusterClient = require('socketcluster-client'); // Create a socket connection const socket = socketClusterClient.create({ hostname: 'localhost', port: 8000 }); // Wait for connection socket.listener('connect').once().then(() => { console.log('Connected!'); }); // Send a message (no response expected) socket.transmit('message', { text: 'Hello server' }); // Send an RPC and wait for response (async () => { try { let result = await socket.invoke('multiply', { a: 5, b: 3 }); console.log('5 * 3 =', result); } catch (err) { console.error('RPC failed:', err.message); } })(); // Subscribe to a channel let channel = socket.subscribe('notifications'); (async () => { for await (let message of channel) { console.log('Got notification:', message); } })(); ``` -------------------------------- ### Creating a New AGClientSocket Instance Source: https://github.com/socketcluster/socketcluster-client/blob/master/_autodocs/api-reference/Factory.md Use the create() function to instantiate a new AGClientSocket. This is the recommended method for creating sockets. ```javascript const socket = socketClusterClient.create(options) ``` -------------------------------- ### Get Receiver Backpressure Source: https://github.com/socketcluster/socketcluster-client/blob/master/_autodocs/api-reference/Streams.md Retrieves the total backpressure for a specific receiver. Use this to monitor the message queue buildup for a particular stream. ```javascript const backpressure = socket.getReceiverBackpressure(receiverName) ``` -------------------------------- ### Get Connection State Source: https://github.com/socketcluster/socketcluster-client/blob/master/_autodocs/api-reference/AGClientSocket.md Retrieve the current connection state of the socket. This is useful for conditional logic, such as only transmitting messages when the socket is open. ```javascript if (socket.getState() === 'open') { socket.transmit('ping', {}); } ``` -------------------------------- ### Channel Listener Methods Source: https://github.com/socketcluster/socketcluster-client/blob/master/_autodocs/api-reference/EventHandling.md Provides methods to get event listeners for specific channel events, such as subscribe, subscribeFail, unsubscribe, and subscribeStateChange. ```APIDOC ## Channel Events Channels emit subscription-related events. ### channel.listener(eventName) Get event listener for a channel. ```javascript channel.listener('subscribe') channel.listener('subscribeFail') channel.listener('unsubscribe') channel.listener('subscribeStateChange') ``` **Source:** Via `ag-channel` module ### Channel Subscription Lifecycle Events #### 'subscribe' Emitted when channel subscription succeeds. ```javascript (async () => { let channel = socket.subscribe('myChannel'); for await (let event of channel.listener('subscribe')) { console.log('Subscribed to channel:', channel.name); break; } })(); ``` #### 'subscribeFail' Emitted when subscription fails (e.g., permission denied). ```javascript (async () => { let channel = socket.subscribe('admin'); for await (let error of channel.listener('subscribeFail')) { console.error('Cannot subscribe:', error.message); break; } })(); **Example with retry:** ```javascript (async () => { let channel = socket.subscribe('admin'); for await (let error of channel.listener('subscribeFail')) { console.error('Subscription failed:', error.message); // Retry after delay await new Promise(resolve => setTimeout(resolve, 1000)); channel.subscribe(); } })(); ``` #### 'unsubscribe' Emitted when unsubscribed from channel. ```javascript (async () => { let channel = socket.subscribe('myChannel'); channel.unsubscribe(); for await (let event of channel.listener('unsubscribe')) { console.log('Unsubscribed from channel'); break; } })(); ``` #### 'subscribeStateChange' Emitted when channel state changes. ```javascript (async () => { let channel = socket.subscribe('myChannel'); for await (let change of channel.listener('subscribeStateChange')) { console.log(`State: ${change.oldChannelState} → ${change.newChannelState}`); } })(); ``` ``` -------------------------------- ### Configuration Options Source: https://github.com/socketcluster/socketcluster-client/blob/master/_autodocs/api-reference/SocketClusterClient.md Details the various options available when creating a SocketClusterClient instance, allowing customization of connection and behavior. ```APIDOC ## Configuration All options are optional. Passed to `socketClusterClient.create()`: ```javascript const socket = socketClusterClient.create({ hostname: 'localhost', // Server hostname port: 8000, // Server port secure: false, // Use WSS instead of WS autoConnect: true, // Connect automatically autoReconnect: true, // Auto-reconnect on disconnect connectTimeout: 20000, // Connection timeout (ms) ackTimeout: 10000, // RPC timeout (ms) path: '/socketcluster/', // WebSocket path query: { token: 'xyz' }, // Query parameters authEngine: customAuthEngine, // Custom token storage codecEngine: customCodec // Custom message encoding }); ``` See `configuration.md` for complete option documentation. ``` -------------------------------- ### Create AGClientSocket Instance Source: https://github.com/socketcluster/socketcluster-client/blob/master/_autodocs/api-reference/AGClientSocket.md Instantiate AGClientSocket with configuration options. The constructor automatically calls connect() if autoConnect is true. ```javascript const socket = new AGClientSocket({ hostname: 'localhost', port: 8000, secure: false, autoConnect: true }); ``` -------------------------------- ### Get Signed JWT Authentication Token Source: https://github.com/socketcluster/socketcluster-client/blob/master/_autodocs/api-reference/AGClientSocket.md Retrieves the current signed JWT authentication token as a string. Returns the token or null if not authenticated. ```javascript socket.getSignedAuthToken() ``` -------------------------------- ### Get a Procedure Stream Source: https://github.com/socketcluster/socketcluster-client/blob/master/_autodocs/api-reference/AGClientSocket.md Obtains a stream for handling incoming Remote Procedure Calls (RPCs). This is used to listen for and respond to RPC requests. ```javascript socket.procedure(procedureName) ``` -------------------------------- ### Get All Receivers Backpressure Source: https://github.com/socketcluster/socketcluster-client/blob/master/_autodocs/api-reference/Streams.md Retrieves the total backpressure across all receivers. Provides an overall view of the system's message processing load. ```javascript const backpressure = socket.getAllReceiversBackpressure() ``` -------------------------------- ### Factory: create() Source: https://github.com/socketcluster/socketcluster-client/blob/master/_autodocs/api-reference/SocketClusterClient.md The `create` function is the entry point for creating new SocketCluster client instances. It accepts an options object to configure the connection. ```APIDOC ## create(options) ### Description Creates a new AGClientSocket instance with the specified options. ### Method Factory function ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters (options object) - **hostname** (string) - Required - The hostname of the SocketCluster server. - **port** (number) - Required - The port of the SocketCluster server. - **secure** (boolean) - Optional - Whether to use WSS (true) or WS (false). - **path** (string) - Optional - The path for the WebSocket connection. - **autoReconnect** (boolean) - Optional - Whether to automatically reconnect on disconnect. - **autoReconnectOptions** (object) - Optional - Options for auto-reconnection. - **ackTimeout** (number) - Optional - Timeout in milliseconds for acknowledgments. - **pingInterval** (number) - Optional - Interval in milliseconds for sending pings. - **pingTimeout** (number) - Optional - Timeout in milliseconds for ping responses. - **protocolVersion** (number) - Optional - The protocol version to use. ### Request Example ```javascript const socket = socketClusterClient.create({ hostname: 'localhost', port: 8000, secure: false }); ``` ### Response #### Success Response Returns an AGClientSocket instance. #### Response Example ```javascript // AGClientSocket instance ``` ``` -------------------------------- ### Get Receiver Consumer Backpressure Source: https://github.com/socketcluster/socketcluster-client/blob/master/_autodocs/api-reference/Streams.md Retrieves the backpressure for a specific consumer within a receiver. Useful for fine-grained monitoring of individual consumer performance. ```javascript const backpressure = socket.getReceiverConsumerBackpressure(consumerId) ``` -------------------------------- ### Invalid Configuration: host + hostname Source: https://github.com/socketcluster/socketcluster-client/blob/master/_autodocs/api-reference/Factory.md Illustrates an invalid configuration where both 'host' and 'hostname' options are provided simultaneously, which is not allowed. ```javascript // Invalid socketClusterClient.create({ host: 'localhost:8000', hostname: 'example.com' // Error: conflicting options }); ``` -------------------------------- ### socket.receiver(receiverName) Source: https://github.com/socketcluster/socketcluster-client/blob/master/_autodocs/api-reference/Streams.md Get an async iterable stream for receiving messages with a specific name from the server. This is used for one-way transmissions where no response is expected. ```APIDOC ## socket.receiver(receiverName) ### Description Get a stream for receiving messages with a specific name. ### Method `socket.receiver(receiverName)` ### Parameters #### Path Parameters - **receiverName** (string) - Required - Name of the receiver/event ### Returns `AsyncIterable` - Async iterable stream ### Example ```javascript (async () => { // Listen for 'notification' events from server for await (let message of socket.receiver('notification')) { console.log('Got notification:', message); // Process notification } })(); ``` ``` -------------------------------- ### Connect to SocketCluster Source: https://github.com/socketcluster/socketcluster-client/blob/master/_autodocs/README.md Initiate a connection to the SocketCluster server. Optional parameters can specify connection options. ```javascript socket.connect(options) ``` -------------------------------- ### Listening to Channel Events Source: https://github.com/socketcluster/socketcluster-client/blob/master/_autodocs/api-reference/AGChannel.md Get a stream of specific channel events like 'subscribe', 'subscribeFail', 'unsubscribe', or 'subscribeStateChange' using the `listener()` method. ```APIDOC ## Listening to Channel Events ### Description Get a stream of specific channel events like 'subscribe', 'subscribeFail', 'unsubscribe', or 'subscribeStateChange' using the `listener()` method. ### Method Signature ```javascript channel.listener(eventName) ``` ### Parameters #### Query Parameters - **eventName** (string) - Required - Event name: 'subscribe', 'subscribeFail', 'unsubscribe', 'subscribeStateChange' ### Returns `AsyncIterable` - Async iterable event stream ### Example ```javascript (async () => { let channel = socket.subscribe('news'); // Listen for subscription success for await (let event of channel.listener('subscribe')) { console.log('Subscribed:', event); break; // Usually only fires once } })(); ``` ``` -------------------------------- ### SocketCluster Client Channel Subscription Options Source: https://github.com/socketcluster/socketcluster-client/blob/master/_autodocs/configuration.md Illustrates how to configure options for individual channel subscriptions. This includes waiting for authentication and setting subscription priority. ```javascript const socket = socketClusterClient.create(); socket.subscribe('some-channel', { waitForAuth: true, priority: 10, data: { 'custom-data': 'value' } }); ``` -------------------------------- ### Get a Channel Without Subscribing Source: https://github.com/socketcluster/socketcluster-client/blob/master/README.md Obtain a channel object without immediately subscribing. This allows for deferred subscription or other channel operations before joining. ```javascript (async () => { let myChannel = socket.channel('myChannel'); // Can subscribe to the channel later as a separate step. myChannel.subscribe(); await myChannel.listener('subscribe').once(); // myChannel.state is now 'subscribed'. })(); ```