### Complete MQTTClient Setup in Unity Source: https://bestdocshub.pages.dev/MQTT/getting-started_q= This complete example combines the setup of connection options (including TLS for secure connection) and the initialization of the `MQTTClient` within a Unity MonoBehaviour's Start method. ```csharp using System.Collections; using System.Collections.Generic; using UnityEngine; using Best.MQTT; using Best.MQTT.Packets.Builders; public class MQTT : MonoBehaviour { // Start is called before the first frame update void Start() { var options = new ConnectionOptionsBuilder() .WithTCP("broker.emqx.io", 8883) .WithTLS() .Build(); var client = new MQTTClient(options); } } ``` -------------------------------- ### Complete Socket.IO Connection Example (C#) Source: https://bestdocshub.pages.dev/Socket.IO/getting-started A comprehensive example demonstrating how to initialize SocketManager, configure connection options (disabling auto-connect), subscribe to the 'connect' event, and manually open the connection. Includes Unity MonoBehaviour lifecycle methods for setup and cleanup. ```csharp using System; using Best.SocketIO; using Best.SocketIO.Events; using UnityEngine; namespace SocketIOExample { public sealed class ChatSample : MonoBehaviour { private SocketManager manager; // Unity Start event void Start() { // Create and setup SocketOptions SocketOptions options = new SocketOptions(); options.AutoConnect = false; // Create and setup SocketManager this.manager = new SocketManager(new Uri("http://localhost:3000"), options); // Set subscriptions manager.Socket.On(SocketIOEventTypes.Connect, OnConnected); // Start connecting to the server this.manager.Open(); } // Connected event handler implementation void OnConnected(ConnectResponse resp) { Debug.Log("Connected!"); } // Unity OnDestroy event void OnDestroy() { this.manager?.Close(); this.manager = null; } } } ``` -------------------------------- ### Full STOMP Client Example in C# (Unity) Source: https://bestdocshub.pages.dev/STOMP/getting-started This C# script provides a complete example of a STOMP client implementation within a Unity project. It includes connecting to a WebSocket-based STOMP broker, handling connection events, setting up subscriptions, and logging messages. It utilizes the `Best.STOMP` library. ```csharp using Best.HTTP.Request.Authentication; using Best.STOMP; using Best.STOMP.Builders; using System; using UnityEngine; public class STOMPPlayground : MonoBehaviour { Client stompClient; public void Start() { stompClient = new Client(); stompClient.OnConnected += OnConnected; stompClient.OnDisconnected += OnDisconnected; var parameters = new ConnectParametersBuilder() .WithHost("localhost", 15674) .WithTransport(SupportedTransports.WebSocket).WithPath("/ws") .WithVirtualHost("/") .WithCredentials(new Credentials("guest", "guest")) .Build(); stompClient.BeginConnect(parameters); } private void OnConnected(Client client, ServerParameters data, IncomingFrame frame) { Debug.Log($"OnConnected('{data.Id}', '{data.Server}')"); client.CreateSubscriptionBuilder("/queue/test") .WithCallback(OnTestQueueCallback) .WithAcknowledgmentCallback(OnSubsriptionAck) .BeginSubscribe(); } private void OnSubsriptionAck(Client client, Subscription subscription, IncomingFrame frame) => Debug.Log($"Subscription created: {subscription.Destination}"); private void OnTestQueueCallback(Client client, Subscription subscription, Message message) { Debug.Log($"[{subscription.Destination}]: {message}"); } private void OnDisconnected(Client client, Error error) => Debug.Log($"OnDisconnected({client}, {error})"); } ``` -------------------------------- ### Initializing MQTTClient Instance Source: https://bestdocshub.pages.dev/MQTT/getting-started_q= This code demonstrates the creation of an `MQTTClient` instance by passing a pre-configured `ConnectionOptions` object to its constructor. ```csharp var client = new MQTTClient(options); ``` -------------------------------- ### Initial C# Script Setup for MQTTClient in Unity Source: https://bestdocshub.pages.dev/MQTT/getting-started_q= This snippet demonstrates the basic C# script structure required for using the MQTTClient in Unity. It includes adding necessary namespaces and setting up a MonoBehaviour class. ```csharp using System.Collections; using System.Collections.Generic; using UnityEngine; using Best.MQTT; using Best.MQTT.Packets.Builders; public class MQTT : MonoBehaviour { // Start is called before the first frame update void Start() { } } ``` -------------------------------- ### Unity MQTT Client Setup and Connection Source: https://bestdocshub.pages.dev/MQTT/getting-started_q= This C# script demonstrates how to initialize an MQTT client in Unity using the Best.MQTT library. It configures connection options including TCP endpoint and TLS, and sets up event handlers for state changes and disconnections. The client then attempts to connect to the MQTT broker. ```csharp using System.Collections; using System.Collections.Generic; using UnityEngine; using Best.MQTT; using Best.MQTT.Packets.Builders; public class MQTT : MonoBehaviour { MQTTClient client; // Start is called before the first frame update void Start() { client = new MQTTClientBuilder() .WithOptions(new ConnectionOptionsBuilder().WithTCP("broker.emqx.io", 8883).WithTLS()) .WithEventHandler(OnDisconnected) .WithEventHandler(OnStateChanged) .WithEventHandler(OnError) .CreateClient(); client.BeginConnect(ConnectPacketBuilderCallback); } private void OnDestroy() { client?.CreateDisconnectPacketBuilder() .WithReasonCode(DisconnectReasonCodes.NormalDisconnection) .WithReasonString("Bye") .BeginDisconnect(); } private ConnectPacketBuilder ConnectPacketBuilderCallback(MQTTClient client, ConnectPacketBuilder builder) { return builder; } private void OnStateChanged(MQTTClient client, ClientStates oldState, ClientStates newState) { Debug.Log($"{oldState} => {newState}"); } private void OnDisconnected(MQTTClient client, DisconnectReasonCodes code, string reason) { Debug.Log($"OnDisconnected - code: {code}, reason: '{reason}'"); } private void OnError(MQTTClient client, string reason) { Debug.Log($"OnError reason: '{reason}'"); } } ``` -------------------------------- ### Send POST Request with Form Data (C#) Source: https://bestdocshub.pages.dev/HTTP/getting-started_q= Example of sending a POST request with multipart form data using Best.HTTP in Unity. It includes setting up the request, adding form fields, sending the request, and handling the response callback for success or errors. ```csharp using Best.HTTP; using Best.HTTP.Request.Upload.Forms; using UnityEngine; public sealed class HTTPTest : MonoBehaviour { private void Start() { // 1. Create request with a callback var request = HTTPRequest.CreatePost("https://httpbin.org/post", RequestFinishedCallback); // 2. Setup request parameters request.UploadSettings.UploadStream = new MultipartFormDataStream() .AddField("Field Name 1", "Field value 1") .AddField("Field Name 2", "Field value 2"); // 3. Send request request.Send(); } // 4. This callback is called when the request is finished. It might finished because of an error! private void RequestFinishedCallback(HTTPRequest req, HTTPResponse resp) { switch(req.State) { case HTTPRequestStates.Finished: if (resp.IsSuccess) { // 5. Here we can process the server's response Debug.Log("Upload finished succesfully!"); } else { // 6. Error handling Debug.Log($"Server sent an error: {resp.StatusCode}-{resp.Message}"); } break; default: // 6. Error handling Debug.LogError($"Request finished with error! Request state: {req.State}"); break; } } } ``` -------------------------------- ### Full STOMP Client Setup and Connection in C# Source: https://bestdocshub.pages.dev/STOMP/getting-started This complete C# script for Unity integrates all the necessary steps: namespace declarations, client initialization, connection event handling, parameter configuration, and initiating the STOMP connection. It allows the client to connect to a RabbitMQ broker via WebSockets. ```csharp using Best.HTTP.Request.Authentication; using Best.STOMP; using Best.STOMP.Builders; using System; using UnityEngine; public class STOMPPlayground : MonoBehaviour { Client stompClient; public void Start() { stompClient = new Client(); stompClient.OnConnected += OnConnected; stompClient.OnDisconnected += OnDisconnected; var parameters = new ConnectParametersBuilder() .WithHost("localhost", 15674) .WithTransport(SupportedTransports.WebSocket).WithPath("/ws") .WithVirtualHost("/") .WithCredentials(new Credentials("guest", "guest")) .Build(); stompClient.BeginConnect(parameters); } private void OnConnected(Client client, ServerParameters data, IncomingFrame frame) { Debug.Log($"OnConnected('{data.Id}', '{data.Server}')"); } private void OnDisconnected(Client client, Error error) => Debug.Log($"OnDisconnected({client}, {error})"); } ``` -------------------------------- ### Disconnect MQTT Client with Builder Pattern (C#) Source: https://bestdocshub.pages.dev/MQTT/getting-started_q= This example illustrates how to gracefully disconnect from an MQTT server using the builder pattern. It allows specifying a reason code and a reason string for the disconnection. ```csharp private void OnDestroy() { client?.CreateDisconnectPacketBuilder() .WithReasonCode(DisconnectReasonCodes.NormalDisconnection) .WithReasonString("Bye") .BeginDisconnect(); } ``` -------------------------------- ### Implement Download Streaming with DownloadContentStream Source: https://bestdocshub.pages.dev/HTTP/upgrade-guide This example shows how to use DownloadContentStream for efficient download streaming. It includes setting up the request, handling the start of the download, and processing incoming data chunks in a coroutine. This replaces older streaming mechanisms like OnStreamingData. ```csharp protected override void Start() { base.Start(); _request = HTTPRequest.CreateGet(this._baseAddress, OnRequestFinishedCallack); _request.DownloadSettings.OnDownloadStarted += OnDownloadStarted; _request.RetrySettings.MaxRetries = 0; _request.Send(); AddUIText("Connecting..."); } private void OnDownloadStarted(HTTPRequest req, HTTPResponse resp, DownloadContentStream stream) { AddUIText("Download started!"); StartCoroutine(ParseContent(stream)); } IEnumerator ParseContent(DownloadContentStream stream) { try { while (!stream.IsCompleted) { if (stream.TryTake(out var buffer)) { using var _ = buffer.AsAutoRelease(); try { var str = Encoding.UTF8.GetString(buffer.Data, buffer.Offset, buffer.Count).TrimEnd(); AddUIText(str); } catch { } } yield return null; } } finally { stream.Dispose(); } } ``` -------------------------------- ### Create HTTP Request (C#) Source: https://bestdocshub.pages.dev/HTTP/getting-started_q= Demonstrates different ways to create HTTPRequest objects in C# using Best.HTTP. It shows static factory methods for common HTTP methods (GET, POST, PUT) and using constructors for more flexibility, including specifying the HTTP method and a callback. ```csharp // Using static factory methods var request = HTTPRequest.CreateGet("https://example.com", callback); var request = HTTPRequest.CreatePost("https://example.com/post", callback); var request = HTTPRequest.CreatePut("https://example.com/put", callback); // Using constructors var request = new HTTPRequest("https://example.com", callback); var request = new HTTPRequest("https://example.com/post", HTTPMethods.Post, callback); var request = new HTTPRequest("https://example.com/put", HTTPMethods.Put, callback); ``` -------------------------------- ### Connecting to the Server Source: https://bestdocshub.pages.dev/SignalR/getting-started Provides examples for initiating the connection to the SignalR server using `StartConnect` or the asynchronous `ConnectAsync` method. It also shows how to define a callback for connection events. ```APIDOC ## Connecting to the Server ### Description Establishes a connection to the SignalR server using either `StartConnect` or `ConnectAsync`. Allows setting up callbacks for connection events. ### Method `StartConnect` or `ConnectAsync` ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example **Using `StartConnect`:** ```csharp var hub = new HubConnection(new Uri("https://server/hub"), new JsonProtocol(new LitJsonEncoder())); hub.OnConnected = (hub) => Debug.Log("Connected!"); hub.StartConnect(); ``` **Using `ConnectAsync`:** ```csharp var hub = new HubConnection(new Uri("https://server/hub"), new JsonProtocol(new LitJsonEncoder())); await hub.ConnectAsync(); Debug.Log("Connected!"); ``` ### Response #### Success Response (200) Connection established. #### Response Example N/A ``` -------------------------------- ### EventSource Initialization Source: https://bestdocshub.pages.dev/Server-Sent%20Events/getting-started Establishes a connection to a Server-Sent Events endpoint. ```APIDOC ## POST /websites/bestdocshub_pages_dev/EventSource ### Description Initializes and connects to a Server-Sent Events (SSE) endpoint. This is a one-way communication protocol where the server sends data to the client. ### Method POST ### Endpoint /websites/bestdocshub_pages_dev/EventSource ### Parameters #### Query Parameters - **url** (string) - Required - The URL of the Server-Sent Events endpoint. ### Request Example ```json { "url": "https://server/sse" } ``` ### Response #### Success Response (200) - **EventSource** (object) - An instance of the EventSource client. #### Response Example ```json { "EventSource": "[EventSource Object]" } ``` ``` -------------------------------- ### Creating MQTT Connection Options with ConnectionOptionsBuilder Source: https://bestdocshub.pages.dev/MQTT/getting-started_q= This code shows how to create a `ConnectionOptions` instance using `ConnectionOptionsBuilder` for establishing a TCP connection to an MQTT broker. It specifies the host and port. ```csharp var options = new ConnectionOptionsBuilder() .WithTCP("broker.emqx.io", 1883) .Build(); ``` -------------------------------- ### Initiate MQTT Connection with BeginConnect (C#) Source: https://bestdocshub.pages.dev/MQTT/getting-started_q= This snippet shows how to initiate a non-blocking connection to an MQTT server using `BeginConnect`. It requires a callback function to build the connect packet after the transport is established. ```csharp client.BeginConnect(ConnectPacketBuilderCallback); private ConnectPacketBuilder ConnectPacketBuilderCallback(MQTTClient client, ConnectPacketBuilder builder) { return builder; } ``` -------------------------------- ### Send STOMP Message in C# Source: https://bestdocshub.pages.dev/STOMP/getting-started_q= This C# code snippet shows how to send a message to a STOMP broker. It utilizes the `CreateMessageBuilder` method, sets the message content and optional headers. It includes two examples. The first uses `BeginSend` and the second uses `SendAsync`. ```csharp client.CreateMessageBuilder("/queue/test") .WithContent("Hello Text World!") .WithHeader("custom-header", "custom header value!") .WithAcknowledgmentCallback((client, frame) => Debug.Log("Message Sent & Processed!")) .BeginSend(); ``` ```csharp await client.CreateMessageBuilder("/queue/test") .WithContent("Hello Text World!") .WithHeader("custom-header", "custom header value!") .SendAsync(); Debug.Log("Message Sent & Processed!"); ``` -------------------------------- ### Stream Downloaded Content with BestHTTP's DownloadContentStream Source: https://bestdocshub.pages.dev/HTTP/upgrade-guide_q= Illustrates how to use the DownloadContentStream in BestHTTP for efficient handling of downloaded content. This example shows setting up a GET request, registering a callback for when the download starts, and then processing the content in chunks within a coroutine. It emphasizes proper stream disposal and error handling. ```csharp protected override void Start() { base.Start(); // Create a regular get request with a regular callback too. We still need a callback, // because it might encounter an error before able to start a download. _request = HTTPRequest.CreateGet(this._baseAddress, OnRequestFinishedCallack); // Request a notification when download starts. This callback will be fired when // the status code suggests that we can expect actual content (2xx status codes). _request.DownloadSettings.OnDownloadStarted += OnDownloadStarted; // Don't want to retry when there's a failure _request.RetrySettings.MaxRetries = 0; // Start processing the request _request.Send(); AddUIText("Connecting..."); } private void OnDownloadStarted(HTTPRequest req, HTTPResponse resp, DownloadContentStream stream) { AddUIText("Download started!"); // We can expect content from the server, start our logic. StartCoroutine(ParseContent(stream)); } IEnumerator ParseContent(DownloadContentStream stream) { try { while (!stream.IsCompleted) { // Try to take out a download segment from the Download Stream. if (stream.TryTake(out var buffer)) { // Make sure that the buffer is released back to the BufferPool. using var _ = buffer.AsAutoRelease(); try { // Try to create a string from the downloaded content var str = Encoding.UTF8.GetString(buffer.Data, buffer.Offset, buffer.Count).TrimEnd(); // And display it in the UI AddUIText(str); } catch { } } yield return null; } } finally { // Don't forget to Dispose the stream! stream.Dispose(); } } ``` -------------------------------- ### Initialize TLSSecurity Setup Source: https://bestdocshub.pages.dev/TLS%20Security/getting-started_q= Initializes the TLS Security addon by calling `TLSSecurity.Setup()` during application startup. This method installs the addon as the default TlsClient factory, loads necessary databases into memory, and writes them to the persistent data path. It includes an update mechanism that checks database hashes to ensure the latest version is used, thereby reducing runtime memory requirements. ```csharp #if !UNITY_WEBGL || UNITY_EDITOR using Best.TLSSecurity; TLSSecurity.Setup(); #endif ``` -------------------------------- ### Subscribe to STOMP Queue in C# Source: https://bestdocshub.pages.dev/STOMP/getting-started_q= This code snippet demonstrates how to subscribe to a STOMP queue. It utilizes the `CreateSubscriptionBuilder` method, sets up callbacks for acknowledgments and message handling, and starts the subscription process. It includes the `OnConnected`, `OnSubsriptionAck`, and `OnTestQueueCallback` methods to handle events related to the subscription. ```csharp client.CreateSubscriptionBuilder("/queue/test") .WithCallback(OnTestQueueCallback) .WithAcknowledgmentCallback(OnSubsriptionAck) .BeginSubscribe(); private void OnSubsriptionAck(Client client, Subscription subscription, IncomingFrame frame) => Debug.Log($"Subscription created: {subscription.Destination}"); private void OnTestQueueCallback(Client client, Subscription subscription, Message message) { Debug.Log($"[{subscription.Destination}]: {message}"); } ``` -------------------------------- ### Create MQTT Client with Builder Pattern (C#) Source: https://bestdocshub.pages.dev/MQTT/getting-started_q= This code demonstrates a more compact way to create and configure an MQTT client using the `MQTTClientBuilder`. It allows setting connection options and event handlers in a fluent API style. ```csharp client = new MQTTClientBuilder() .WithOptions(new ConnectionOptionsBuilder().WithTCP("broker.emqx.io", 1883)) .WithEventHandler(OnStateChanged) .WithEventHandler(OnDisconnected) .WithEventHandler(OnError) .CreateClient(); ``` -------------------------------- ### ConnectionOptionsBuilder Usage Examples Source: https://bestdocshub.pages.dev/MQTT/api-reference/MQTT/ConnectionOptionsBuilder Examples demonstrating how to use the ConnectionOptionsBuilder to create connection options and an MQTT client. ```APIDOC ## ConnectionOptionsBuilder Builder class to help creating ConnectionOptions instances. ### Description This class provides a fluent API for building `ConnectionOptions` for an MQTT client. ### Methods #### `WithTCP(string host, int port)` Adds options for a TCP connection. - **host** (string) - Required - The hostname or IP address of the MQTT broker. - **port** (int) - Required - The port number of the MQTT broker. #### `WithWebSocket(string uri, int port)` Adds options for a WebSocket connection. - **uri** (string) - Required - The WebSocket endpoint URI. - **port** (int) - Required - The port number for the WebSocket connection. #### `WithTLS()` Configures the client to use TLS for secure communication. #### `WithPath(string path)` Specifies the path for the WebSocket transport. - **path** (string) - Required - The path to use for the WebSocket connection. #### `WithProtocolVersion(SupportedProtocolVersions version)` Sets the MQTT protocol version to use for the connection. - **version** (SupportedProtocolVersions) - Required - The MQTT protocol version (e.g., `MQTT_3_1_1`). #### `CreateClient()` Creates an `MQTTClient` object with the configured options. Returns: - `MQTTClient` - An instance of the MQTT client. #### `Build()` Builds and returns the final `ConnectionOptions` instance. Returns: - `ConnectionOptions` - The configured connection options. ### Examples #### Example 1: Creating Connection Options This example creates `ConnectionOptions` to connect to `localhost` on port `1883` using TCP and MQTT protocol version `v3.1.1`. ```csharp var options = new ConnectionOptionsBuilder() .WithTCP("localhost", 1883) .WithProtocolVersion(SupportedProtocolVersions.MQTT_3_1_1) .Build(); var client = new MQTTClient(options); ``` #### Example 2: Creating MQTT Client Directly This example demonstrates creating the `MQTTClient` directly using the builder. ```csharp var client = new ConnectionOptionsBuilder() .WithTCP("localhost", 1883) .WithProtocolVersion(SupportedProtocolVersions.MQTT_3_1_1) .CreateClient(); ``` ``` -------------------------------- ### Declare Namespaces for Best STOMP in Unity Source: https://bestdocshub.pages.dev/STOMP/getting-started_q= This snippet shows the necessary using directives for implementing Best STOMP functionality in a Unity C# script. It includes namespaces for Best HTTP, Best STOMP, and general Unity functionalities. ```csharp using Best.HTTP.Request.Authentication; using Best.STOMP; using Best.STOMP.Builders; using System; using UnityEngine; ``` -------------------------------- ### Create MQTT Connection with Options (C#) Source: https://bestdocshub.pages.dev/MQTT/api-reference/MQTT/ConnectionOptions A simple example demonstrating how to create a new MQTTClient instance with specified connection options. It sets the host, port, and protocol version for the connection. This requires the MQTTClient library. ```csharp ConnectionOptions options = new ConnectionOptions { Host = "localhost", Port = 1883, ProtocolVersion = SupportedProtocolVersions.MQTT_3_1_1 }; var client = new MQTTClient(options); ``` -------------------------------- ### Create MQTTClient using Builder Source: https://bestdocshub.pages.dev/MQTT/api-reference/MQTT/ConnectionOptionsBuilder Shows how to use the ConnectionOptionsBuilder to directly create an MQTTClient instance. This combines building the options and instantiating the client in one fluent chain. ```csharp var client = new ConnectionOptionsBuilder() .WithTCP("localhost", 1883) .WithProtocolVersion(SupportedProtocolVersions.MQTT_3_1_1) .CreateClient(); ``` -------------------------------- ### Start and Stop EventSource Connection Source: https://bestdocshub.pages.dev/Server-Sent%20Events/getting-started Provides methods to explicitly open and close the connection to the Server-Sent Events server. Use `Open()` to initiate communication and `Close()` to terminate it. ```csharp sse.Open(); ``` ```csharp sse.Close(); ``` -------------------------------- ### HubConnection with Options Source: https://bestdocshub.pages.dev/SignalR/getting-started Demonstrates how to initialize a HubConnection with additional options by passing a `HubOptions` instance to the constructor. ```APIDOC ## HubConnection Setup with Options ### Description Initializes a `HubConnection` object with custom `HubOptions` for advanced configuration. ### Method Constructor ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```csharp HubOptions options = new HubOptions(); hub = new HubConnection(new Uri("https://server/hub"), new JsonProtocol(new LitJsonEncoder()), options); ``` ### Response #### Success Response (200) N/A #### Response Example N/A ``` -------------------------------- ### EventSource Connection Management Source: https://bestdocshub.pages.dev/Server-Sent%20Events/getting-started Provides methods to open and close the connection to the SSE server. ```APIDOC ## Connection Management for EventSource ### Description These endpoints manage the lifecycle of the Server-Sent Events connection, allowing you to open and close the communication channel. ### Method POST ### Endpoint /websites/bestdocshub_pages_dev/EventSource/{action} ### Parameters #### Path Parameters - **action** (string) - Required - The action to perform. Accepted values are `open` and `close`. ### Request Example ```json { "action": "open" } ``` ### Response #### Success Response (200) - **status** (string) - Indicates the success of the operation (e.g., "Connection opened successfully.", "Connection closed."). #### Response Example ```json { "status": "Connection opened successfully." } ``` ``` -------------------------------- ### MQTT Client Connection with ConnectPacketBuilderCallback Source: https://bestdocshub.pages.dev/MQTT/api-reference/Builders/ConnectPacketBuilder_q= Demonstrates how to initiate an MQTT client connection using a callback function with the ConnectPacketBuilder. The callback receives the builder and can optionally modify it before returning. ```csharp var options = new ConnectionOptionsBuilder() .WithTCP("test.mosquitto.org", 1883) .Build(); client = new MQTTClient(options); client.BeginConnect(ConnectPacketBuilderCallback); ConnectPacketBuilder ConnectPacketBuilderCallback(MQTTClient client, ConnectPacketBuilder builder) { return builder; } ``` -------------------------------- ### EventSource Event Handling Source: https://bestdocshub.pages.dev/Server-Sent%20Events/getting-started Covers subscribing and unsubscribing from various events emitted by the Server-Sent Events connection. ```APIDOC ## Event Handling for EventSource ### Description Manage event listeners for the EventSource connection. This includes listening for general connection events, messages, custom events, errors, and reconnection attempts. ### Method POST ### Endpoint /websites/bestdocshub_pages_dev/EventSource/events/{eventName} ### Parameters #### Path Parameters - **eventName** (string) - Optional - The name of the event to subscribe to or unsubscribe from. Use `message` for general messages, `open` for connection open, `error` for errors, `retry` for reconnection attempts. If omitted, applies to general message events. #### Query Parameters - **action** (string) - Required - The action to perform. Accepted values are `subscribe` and `unsubscribe`. ### Request Example ```json { "action": "subscribe" } ``` ### Response #### Success Response (200) - **status** (string) - Indicates the success of the subscription or unsubscription (e.g., "Event 'userLogon' subscribed.", "Unsubscribed from 'message' event."). #### Response Example ```json { "status": "Event 'message' subscribed." } ``` ``` -------------------------------- ### Unity MQTT Client Setup and Connection Source: https://bestdocshub.pages.dev/MQTT/getting-started/publish This snippet shows the initialization of an MQTT client in Unity using the Best.MQTT library. It configures connection options, event handlers, and initiates the connection process. Dependencies include the Best.MQTT library and Unity. ```csharp using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using Best.MQTT; using Best.MQTT.Packets.Builders; public class MQTT : MonoBehaviour { MQTTClient client; // Start is called before the first frame update void Start() { client = new MQTTClientBuilder() .WithOptions(new ConnectionOptionsBuilder().WithTCP("broker.emqx.io", 1883)) .WithEventHandler(OnConnected) .WithEventHandler(OnDisconnected) .WithEventHandler(OnStateChanged) .WithEventHandler(OnError) .CreateClient(); client.BeginConnect(ConnectPacketBuilderCallback); } private void OnDestroy() { client?.CreateDisconnectPacketBuilder() .WithReasonCode(DisconnectReasonCodes.NormalDisconnection) .WithReasonString("Bye") .BeginDisconnect(); } private ConnectPacketBuilder ConnectPacketBuilderCallback(MQTTClient client, ConnectPacketBuilder builder) { return builder; } private void OnStateChanged(MQTTClient client, ClientStates oldState, ClientStates newState) { Debug.Log($"{oldState} => {newState}"); } private void OnDisconnected(MQTTClient client, DisconnectReasonCodes code, string reason) { Debug.Log($"OnDisconnected - code: {code}, reason: '{reason}'"); } private void OnError(MQTTClient client, string reason) { Debug.Log($"OnError reason: '{reason}'"); } } ``` -------------------------------- ### ConnectionOptionsBuilder Usage Examples Source: https://bestdocshub.pages.dev/MQTT/api-reference/MQTT/ConnectionOptionsBuilder_q= Examples demonstrating how to use the ConnectionOptionsBuilder to create connection options and an MQTT client. ```APIDOC ## ConnectionOptionsBuilder Usage Examples ### Description Examples demonstrating how to use the ConnectionOptionsBuilder to create connection options and an MQTT client. ### Example 1: Building Connection Options This example shows how to build `ConnectionOptions` for a TCP connection using MQTT version 3.1.1. ```csharp var options = new ConnectionOptionsBuilder() .WithTCP("localhost", 1883) .WithProtocolVersion(SupportedProtocolVersions.MQTT_3_1_1) .Build(); var client = new MQTTClient(options); ``` ### Example 2: Creating MQTT Client Directly This example demonstrates creating an `MQTTClient` directly using the builder. ```csharp var client = new ConnectionOptionsBuilder() .WithTCP("localhost", 1883) .WithProtocolVersion(SupportedProtocolVersions.MQTT_3_1_1) .CreateClient(); ``` ``` -------------------------------- ### Example Server Method Implementation Source: https://bestdocshub.pages.dev/SignalR/getting-started_q= A basic C# implementation of a SignalR Hub on the server-side. This example defines a `TestHub` class with a `Send` method that broadcasts a message to all connected clients, including the sender's connection ID. ```csharp public class TestHub : Hub { public Task Send(string message) { return Clients.All.SendAsync("Send", $"{Context.ConnectionId}: {message}"); } } ``` -------------------------------- ### Initialize STOMP Client and Callbacks in C# Source: https://bestdocshub.pages.dev/STOMP/getting-started This code initializes the STOMP client and subscribes to connection events (OnConnected and OnDisconnected) within the Start method of a Unity MonoBehaviour script. It defines handler methods for these events to log connection status. ```csharp public void Start() { stompClient = new Client(); stompClient.OnConnected += OnConnected; stompClient.OnDisconnected += OnDisconnected; } private void OnConnected(Client client, ServerParameters serverParams, IncomingFrame frame) { Debug.Log($"OnConnected('{serverParams.Id}', '{serverParams.Server}')"); } private void OnDisconnected(Client client, Error error) => Debug.Log($"OnDisconnected({client}, {error})"); ``` -------------------------------- ### Initialize EventSource Connection Source: https://bestdocshub.pages.dev/Server-Sent%20Events/getting-started Establishes a connection to a Server-Sent Events endpoint using the EventSource class. This is the first step to receiving data from the server. ```csharp using Best.ServerSentEvents; var sse = new EventSource(new Uri("https://server/sse")); ``` -------------------------------- ### Connecting to the Server Source: https://bestdocshub.pages.dev/SignalR/getting-started_q= This section explains how to establish a connection to the SignalR server using `StartConnect` or `ConnectAsync`. ```APIDOC ## Connecting to the Server ### Description Initiate the connection process to the SignalR server using either the `StartConnect` method or the asynchronous `ConnectAsync` method. ### Method `StartConnect()` or `ConnectAsync()` ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```csharp // Using StartConnect var hub = new HubConnection(new Uri("https://server/hub"), new JsonProtocol(new LitJsonEncoder())); hub.OnConnected = (hub) => Debug.Log("Connected!"); hub.StartConnect(); // Using ConnectAsync var hub = new HubConnection(new Uri("https://server/hub"), new JsonProtocol(new LitJsonEncoder())); await hub.ConnectAsync(); Debug.Log("Connected!"); ``` ### Response #### Success Response (Connection Established) - **OnConnected Callback**: Executes upon successful connection. #### Response Example ``` Connected! ``` ``` -------------------------------- ### Manage EventSource Reconnections Source: https://bestdocshub.pages.dev/Server-Sent%20Events/getting-started Configures reconnection behavior by subscribing to the `OnRetry` event. Returning `true` allows automatic reconnection attempts, while `false` disables them. ```csharp sse.OnRetry += OnEventSourceRetry; bool OnEventSourceRetry(EventSource source) { Debug.log("Attempting reconnection..."); return true; // Allow reconnection. Returning false will prevent retry. } ``` -------------------------------- ### Async POST Request with Form Data in C# Source: https://bestdocshub.pages.dev/HTTP/getting-started_q= Demonstrates how to create and send an asynchronous HTTP POST request with multipart form data using the Best.HTTP library. It includes setting up the request, awaiting the response, and handling both successful responses and potential exceptions. This method is suitable for uploading data to a server endpoint. ```csharp using Best.HTTP; using Best.HTTP.Request.Upload.Forms; using UnityEngine; public sealed class HTTPTest : MonoBehaviour { private async void Start() { // 1. Create request var request = HTTPRequest.CreatePost("https://httpbin.org/post"); // 2. Setup request.UploadSettings.UploadStream = new MultipartFormDataStream() .AddField("Field Name 1", "Field value 1") .AddField("Field Name 2", "Field value 2"); try { // 3. Send & wait for completion var response = await request.GetHTTPResponseAsync(); // 5. Process response if (response.IsSuccess) Debug.Log("Upload finished succesfully!"); else Debug.LogError($"Server sent an error: {response.StatusCode}-{response.Message}"); } catch (AsyncHTTPException e) { // 6. Error handling Debug.LogError($"Request finished with error! Error: {e.Message}"); } } } ``` -------------------------------- ### Namespace Update Example (C#) Source: https://bestdocshub.pages.dev/HTTP/upgrade-guide_q= Demonstrates the change in 'using' directives for Best HTTP package namespaces when upgrading to v3.x. It shows the transition from older, broader namespaces to more specific ones introduced in the new version. ```csharp using BestHTTP; using BestHTTP.Logger; ``` ```csharp using Best.HTTP; using Best.HTTP.Shared; using Best.HTTP.Shared.Logger; using Best.HTTP.Proxies; ``` -------------------------------- ### Update UserAgent in BestHTTP Source: https://bestdocshub.pages.dev/HTTP/upgrade-guide_q= Provides an example of how to set the User-Agent string, which now includes package version and Unity runtime version information. ```csharp Assembly thisAssem = typeof(HTTPManager).Assembly; AssemblyName thisAssemName = thisAssem?.GetName(); Version ver = thisAssemName?.Version; UserAgent = $"com.Tivadar.Best.HTTP v{ver}/Unity {UnityEngine.Application.unityVersion}"; ```