### Complete MQTT Client Setup Example Source: https://github.com/benedicht/com.tivadar.best.documentation/blob/main/docs/MQTT/getting-started/index.md A complete example demonstrating the setup of ConnectionOptions with TLS and the instantiation of the MQTTClient within a Unity MonoBehaviour. ```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); } } ``` -------------------------------- ### Full STOMP Client Setup Source: https://github.com/benedicht/com.tivadar.best.documentation/blob/main/docs/STOMP/getting-started/index.md This is a complete example of setting up a STOMP client, connecting to a broker via WebSocket, and establishing a subscription. It includes connection and disconnection event handlers. ```cs 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})"); } ``` -------------------------------- ### Complete Socket.IO Chat Example Source: https://github.com/benedicht/com.tivadar.best.documentation/blob/main/docs/Socket.IO/getting-started/index.md A full example demonstrating Socket.IO integration in a Unity project. It includes setup, connection, event handling, and cleanup. ```cs 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; } } } ``` -------------------------------- ### TLS Security Setup Source: https://github.com/benedicht/com.tivadar.best.documentation/blob/main/docs/TLS Security/getting-started/index.md Call TLSSecurity.Setup() during your application's startup. This installs the addon as the default TlsClient factory and loads necessary TLS databases. It's conditionally compiled for non-WebGL environments. ```csharp #if !UNITY_WEBGL || UNITY_EDITOR using Best.TLSSecurity; TLSSecurity.Setup(); #endif ``` -------------------------------- ### Basic Unity C# Script Setup Source: https://github.com/benedicht/com.tivadar.best.documentation/blob/main/docs/MQTT/getting-started/index.md Initial C# script setup for MQTTClient in Unity, including necessary namespaces and a basic MonoBehaviour structure. Delete the Update function if not needed. ```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() { } } ``` -------------------------------- ### Complete HTTP POST Request Example Source: https://github.com/benedicht/com.tivadar.best.documentation/blob/main/docs/HTTP/getting-started/index.md A full example demonstrating how to create, configure, send, and handle a POST request with form data and a callback. ```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; } } } ``` -------------------------------- ### TLSSecurity Setup Source: https://github.com/benedicht/com.tivadar.best.documentation/blob/main/docs/TLS Security/api-reference/TLSSecurity/TLSSecurity.md Initiates the setup process of the TLS Security package. This method should be called to begin the process of loading certificates and preparing the TLS security environment. ```APIDOC ## Void TLSSecurity.Setup() ### Description Initiates the setup process of the TLS Security package. ### Method Void ### Endpoint TLSSecurity.Setup() ### Parameters None ### Request Example None ### Response #### Success Response Void (no return value) #### Response Example None ``` -------------------------------- ### Install Dependencies Source: https://github.com/benedicht/com.tivadar.best.documentation/blob/main/README.md Install Python dependencies required for building the documentation locally. ```bash pip install -r requirements.txt ``` -------------------------------- ### Create GET Request using Constructor Source: https://github.com/benedicht/com.tivadar.best.documentation/blob/main/docs/HTTP/getting-started/index.md Create a GET request using the HTTPRequest constructor, specifying the URL and a callback. ```csharp var request = new HTTPRequest("https://example.com", callback); ``` -------------------------------- ### Simple Connection Options Example Source: https://github.com/benedicht/com.tivadar.best.documentation/blob/main/docs/MQTT/api-reference/MQTT/ConnectionOptions.md Demonstrates how to create basic connection options for an MQTT client, specifying the host, port, and protocol version. ```cs ConnectionOptions options = new ConnectionOptions { Host = "localhost", Port = 1883, ProtocolVersion = SupportedProtocolVersions.MQTT_3_1_1 }; var client = new MQTTClient(options); ``` -------------------------------- ### Create GET Request with Callback Source: https://github.com/benedicht/com.tivadar.best.documentation/blob/main/docs/HTTP/getting-started/index.md Quickly create a GET request to a specified URL with a callback function to handle the response. ```csharp var request = HTTPRequest.CreateGet("https://example.com", callback); ``` -------------------------------- ### Start the Connection Source: https://github.com/benedicht/com.tivadar.best.documentation/blob/main/docs/Server-Sent Events/getting-started/index.md Open the connection to the Server-Sent Events endpoint. ```csharp sse.Open(); ``` -------------------------------- ### Basic MQTT Connection Setup Source: https://github.com/benedicht/com.tivadar.best.documentation/blob/main/docs/MQTT/api-reference/Builders/ConnectPacketBuilder.md Demonstrates how to initiate an MQTT connection using a ConnectPacketBuilder. The callback function provided to BeginConnect can be used to modify the builder before the connection is established. ```cs 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; } ``` -------------------------------- ### Get HostSettings by String Source: https://github.com/benedicht/com.tivadar.best.documentation/blob/main/docs/HTTP/api-reference/Settings/HostSettingsManager.md Retrieves host settings for a given hostname. Returns default settings if not found. ```APIDOC ## Get [HostSettings](HostSettings.md) ### Description Gets [HostSettings](HostSettings.md) for the host part of the specified hostname. Returns the default settings associated with "*" when not found. ### Method GET ### Endpoint /settings/host ### Parameters #### Query Parameters - **hostname** (String) - Required - The hostname to get settings for. ``` -------------------------------- ### OnDownloadStartedDelegate Source: https://github.com/benedicht/com.tivadar.best.documentation/blob/main/docs/HTTP/api-reference/Settings/OnDownloadStartedDelegate.md Delegate for handling the event when the download of content starts. ```APIDOC ## OnDownloadStartedDelegate(req, resp, stream) ### Description Delegate for handling the event when the download of content starts. ### Parameters - **req**: The request object. - **resp**: The response object. - **stream**: The stream for the download. ``` -------------------------------- ### Complete MQTT Client Example in C# Source: https://github.com/benedicht/com.tivadar.best.documentation/blob/main/docs/MQTT/getting-started/index.md This C# script demonstrates how to initialize and connect an MQTT client using the MQTT library in Unity. It includes configuration for connection options, TLS, and event handlers for state changes, disconnection, and errors. ```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}'"); } } ``` -------------------------------- ### Start WebSocket Connection Source: https://github.com/benedicht/com.tivadar.best.documentation/blob/main/docs/WebSockets/getting-started/index.md Initiate the WebSocket connection process by calling the Open() method. Note that this is a non-blocking call. ```cs var webSocket = new WebSocket(new Uri("wss://websocketserver/ws")); webSocket.Open(); ``` -------------------------------- ### Initial Setup: Add OnConnected Event Handler Source: https://github.com/benedicht/com.tivadar.best.documentation/blob/main/docs/MQTT/getting-started/publish.md Extend the MQTT client setup by adding an event handler for the OnConnected event. This handler is called after a successful connection and before messages can be sent. ```csharp client = new MQTTClientBuilder() // ... .WithEventHandler(OnConnected) // ... .CreateClient(); private void OnConnected(MQTTClient client) { } ``` -------------------------------- ### Begin a STOMP Transaction with Callback Source: https://github.com/benedicht/com.tivadar.best.documentation/blob/main/docs/STOMP/getting-started/transactions.md Start a transaction and provide a callback function to be executed upon acknowledgment of the transaction beginning. ```csharp transaction.Begin((client, tr) => { Debug.Log($"Transaction({tr}) Begin!"); // Additional transactional operations... }); ``` -------------------------------- ### Complete MQTT Client Implementation in Unity Source: https://github.com/benedicht/com.tivadar.best.documentation/blob/main/docs/MQTT/getting-started/subscribe.md A comprehensive Unity script demonstrating the MQTT client setup, connection, subscription, message handling, and disconnection. Includes platform-specific connection options. ```csharp using System; using System.Text; using System.Collections; using System.Collections.Generic; using UnityEngine; using Best.MQTT; using Best.MQTT.Packets.Builders; using Best.MQTT.Packets; public class MQTT : MonoBehaviour { MQTTClient client; // Start is called before the first frame update void Start() { client = new MQTTClientBuilder() #if !UNITY_WEBGL || UNITY_EDITOR .WithOptions(new ConnectionOptionsBuilder().WithTCP("broker.emqx.io", 1883)) #else .WithOptions(new ConnectionOptionsBuilder().WithWebSocket("broker.emqx.io", 8084).WithTLS()) #endif .WithEventHandler(OnConnected) .WithEventHandler(OnDisconnected) .WithEventHandler(OnStateChanged) .WithEventHandler(OnError) .CreateClient(); client.BeginConnect(ConnectPacketBuilderCallback); } private void OnConnected(MQTTClient client) { client.AddTopicAlias("best_mqtt/test_topic"); client.CreateSubscriptionBuilder("best_mqtt/test_topic") .WithMessageCallback(OnMessage) .WithAcknowledgementCallback(OnSubscriptionAcknowledged) .WithMaximumQoS(QoSLevels.ExactlyOnceDelivery) .BeginSubscribe(); client.CreateApplicationMessageBuilder("best_mqtt/test_topic") .WithPayload("Hello MQTT World!") .WithQoS(QoSLevels.ExactlyOnceDelivery) .WithContentType("text/plain; charset=UTF-8") .BeginPublish(); } private void OnMessage(MQTTClient client, SubscriptionTopic topic, string topicName, ApplicationMessage message) { // Convert the raw payload to a string var payload = Encoding.UTF8.GetString(message.Payload.Data, message.Payload.Offset, message.Payload.Count); Debug.Log($"Content-Type: '{message.ContentType}' Payload: '{payload}'"); client.CreateUnsubscribePacketBuilder("best_mqtt/test_topic") .WithAcknowledgementCallback((client, topicFilter, reasonCode) => Debug.Log($"Unsubscribe request to topic filter '{topicFilter}' returned with code: {reasonCode}")) .BeginUnsubscribe(); } private void OnSubscriptionAcknowledged(MQTTClient client, SubscriptionTopic topic, SubscribeAckReasonCodes reasonCode) { if (reasonCode <= SubscribeAckReasonCodes.GrantedQoS2) Debug.Log($"Successfully subscribed with topic filter '{topic.Filter.OriginalFilter}'. QoS granted by the server: {reasonCode}"); else Debug.Log($"Could not subscribe with topic filter '{topic.Filter.OriginalFilter}'! Error code: {reasonCode}"); } 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}'"); } } ``` -------------------------------- ### Initiate MQTT Connection Source: https://github.com/benedicht/com.tivadar.best.documentation/blob/main/docs/MQTT/getting-started/index.md Start the connection process to the MQTT server using BeginConnect. This method is non-blocking and requires a callback to build the connect packet. ```csharp client.BeginConnect(ConnectPacketBuilderCallback); private ConnectPacketBuilder ConnectPacketBuilderCallback(MQTTClient client, ConnectPacketBuilder builder) { return builder; } ``` -------------------------------- ### Using DownloadContentStream for Streaming Downloads Source: https://github.com/benedicht/com.tivadar.best.documentation/blob/main/docs/HTTP/upgrade-guide.md This example demonstrates how to use DownloadContentStream to process downloaded content in segments. Ensure the stream is disposed after use. ```cs 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(); } } ``` -------------------------------- ### Using MessagePackCSharpProtocol Source: https://github.com/benedicht/com.tivadar.best.documentation/blob/main/docs/SignalR/intermediate-topics/encoders.md Instantiates a HubConnection using the MessagePackCSharpProtocol. Requires MessagePack-CSharp package installation and the BEST_SIGNALR_ENABLE_MESSAGEPACK_CSHARP define. ```csharp var hub = new HubConnection(new Uri("https://server/hub"), new MessagePackCSharpProtocol()); ``` -------------------------------- ### Get HostSettings by Uri Source: https://github.com/benedicht/com.tivadar.best.documentation/blob/main/docs/HTTP/api-reference/Settings/HostSettingsManager.md Retrieves host settings for the host part of a given URI. Returns default settings if not found. ```APIDOC ## Get [HostSettings](HostSettings.md) ### Description Gets [HostSettings](HostSettings.md) for the host part of the specified [Uri](https://learn.microsoft.com/en-us/dotnet/api/System.Uri). Returns the default settings associated with "*" when not found. ### Method GET ### Endpoint /settings/host ### Parameters #### Query Parameters - **uri** (Uri) - Required - The Uri to get settings for. ``` -------------------------------- ### Send Message with BeginSend Source: https://github.com/benedicht/com.tivadar.best.documentation/blob/main/docs/STOMP/getting-started/index.md This example demonstrates sending a message to a queue using the `BeginSend` method. It includes setting message content, custom headers, and a callback for when the message is sent and processed. ```cs client.CreateMessageBuilder("/queue/test") .WithContent("Hello Text World!") .WithHeader("custom-header", "custom header value!") .WithAcknowledgmentCallback((client, frame) => Debug.Log("Message Sent & Processed!")) .BeginSend(); ``` -------------------------------- ### Enable and Use MsgPackParser Source: https://github.com/benedicht/com.tivadar.best.documentation/blob/main/docs/Socket.IO/intermediate-topics/parsers.md Demonstrates how to set the MsgPackParser for a SocketManager. This requires specific setup steps including assembly definitions and scripting define symbols. ```csharp var manager = new SocketManager(new Uri("http://localhost:3000")); manager.Parser = new MsgPackParser(); ``` -------------------------------- ### Implement Custom Address Shuffling Algorithm for One Host Source: https://github.com/benedicht/com.tivadar.best.documentation/blob/main/docs/Shared/connections/racing.md Allows you to define a custom algorithm for shuffling IP addresses when establishing TCP connections to a specific host. This example implements a basic random shuffle for 'example.com'. ```cs Best.HTTP.Shared.HTTPManager.PerHostSettings.Get("example.com") .TCPRingmasterSettings.CustomAddressShuffleAlgorithm = (@params) => { var rand = new System.Random(); int n = @params.Addresses.Length; while (n > 1) { int k = rand.Next(n--); (@params.Addresses[n], @params.Addresses[k]) = (@params.Addresses[k], @params.Addresses[n]); } }; ``` -------------------------------- ### Send Message with SendAsync Source: https://github.com/benedicht/com.tivadar.best.documentation/blob/main/docs/STOMP/getting-started/index.md This example shows how to send a message asynchronously using `SendAsync`. It configures message content and custom headers, and logs a confirmation after the message is sent. ```cs await client.CreateMessageBuilder("/queue/test") .WithContent("Hello Text World!") .WithHeader("custom-header", "custom header value!") .SendAsync(); Debug.Log("Message Sent & Processed!"); ``` -------------------------------- ### Complete STOMP Client Setup and Connection Source: https://github.com/benedicht/com.tivadar.best.documentation/blob/main/docs/STOMP/getting-started/index.md This is the final code for a Unity MonoBehaviour that sets up and connects a STOMP client. It includes handling connection and disconnection events, and setting up a subscription. ```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})"); private void OnDisable() => this.stompClient?.BeginDisconnect(); } ``` -------------------------------- ### TLSSecurity WaitForSetupFinish Source: https://github.com/benedicht/com.tivadar.best.documentation/blob/main/docs/TLS Security/api-reference/TLSSecurity/TLSSecurity.md Blocks the current thread until the TLS security setup process is finished. This is useful for ensuring that all necessary security components are ready before proceeding. ```APIDOC ## Void TLSSecurity.WaitForSetupFinish() ### Description Blocks the current thread until setup is finished. ### Method Void ### Endpoint TLSSecurity.WaitForSetupFinish() ### Parameters None ### Request Example None ### Response #### Success Response Void (no return value) #### Response Example None ``` -------------------------------- ### Handle Download Completion with Task.Run Source: https://github.com/benedicht/com.tivadar.best.documentation/blob/main/docs/HTTP/getting-started/downloads.md Modify OnDownloadStarted to use async and Task.Run to consume the download stream on a non-Unity thread. Await the Task.Run call to get the CRC result. ```csharp async void OnDownloadStarted(HTTPRequest req, HTTPResponse resp, DownloadContentStream stream) { Debug.Log("Download Started"); var crc = await Task.Run(() => ConsumeDownloadStream(stream as BlockingDownloadContentStream)); Debug.Log($ ``` -------------------------------- ### Configure HTTP Cache Options Source: https://github.com/benedicht/com.tivadar.best.documentation/blob/main/docs/HTTP/intermediate-topics/caching-internals.md Set new HTTP cache options by creating a new instance. It's advised to do this at the start of the application before any other plugin calls. ```cs HTTPManager.LocalCache?.Dispose(); HTTPManager.LocalCache = new HTTPCacheBuilder() .WithOptions(new HTTPCacheOptionsBuilder() .WithMaxCacheSize(128 * 1024 * 1024) .Build()) .Build(); ``` -------------------------------- ### MQTT Client Setup and Publish Source: https://github.com/benedicht/com.tivadar.best.documentation/blob/main/docs/MQTT/getting-started/publish.md This C# script demonstrates how to initialize an MQTT client, connect to a broker, and publish a message. It includes event handlers for connection, disconnection, state changes, and errors. The message is published with 'ExactlyOnceDelivery' QoS and a specified content type. ```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 OnConnected(MQTTClient client) { client.AddTopicAlias("best_mqtt/test_topic"); client.CreateApplicationMessageBuilder("best_mqtt/test_topic") .WithPayload("Hello MQTT World!") .WithQoS(Best.MQTT.Packets.QoSLevels.ExactlyOnceDelivery) .WithContentType("text/plain; charset=UTF-8") .BeginPublish(); } 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}'"); } } ``` -------------------------------- ### Serve Documentation Locally Source: https://github.com/benedicht/com.tivadar.best.documentation/blob/main/README.md Use mkdocs serve to preview the documentation changes locally before deployment. ```bash mkdocs serve ``` -------------------------------- ### Create GET Request Source: https://github.com/benedicht/com.tivadar.best.documentation/blob/main/docs/HTTP/api-reference/HTTP/HTTPRequest.md Creates an HTTP GET request. Supports both string URLs and Uri objects, with optional callbacks for completion. ```APIDOC ## Create GET Request (String URL) ### Description Creates an HTTP GET request with the specified URL. ### Method GET ### Endpoint [URL provided as string] ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ## Create GET Request (Uri Object) ### Description Creates an HTTP GET request with the specified URI. ### Method GET ### Endpoint [URI object] ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ## Create GET Request with Callback (String URL) ### Description Creates an HTTP GET request with the specified URL and registers a callback function to be called when the request is fully processed. ### Method GET ### Endpoint [URL provided as string] ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Callback [OnRequestFinishedDelegate] ## Create GET Request with Callback (Uri Object) ### Description Creates an HTTP GET request with the specified URI and registers a callback function to be called when the request is fully processed. ### Method GET ### Endpoint [URI object] ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Callback [OnRequestFinishedDelegate] ``` -------------------------------- ### Get a Byte Array from BufferPool Source: https://github.com/benedicht/com.tivadar.best.documentation/blob/main/docs/Shared/memory/bufferpool.md Use the Get function to fetch a byte array. The returned buffer might be larger than requested if `canBeLarger` is true. ```csharp byte[] buffer = BufferPool.Get(size, canBeLarger); ``` -------------------------------- ### Setting up HubConnection with PlayFabAuthenticator Source: https://github.com/benedicht/com.tivadar.best.documentation/blob/main/docs/SignalR/intermediate-topics/authentication/PlayFabPubSub.md Demonstrates how to initialize a `HubConnection` and assign the custom `PlayFabAuthenticator` to its `AuthenticationProvider` property. ```csharp string titleId = "..."; string entityToken = "..."; var connection = new HubConnection(new Uri($"https://{titleId}.playfabapi.com/pubsub"), new JsonProtocol(new LitJsonEncoder())); connection.AuthenticationProvider = new PlayFabAuthenticator(connection, entityToken); // add callbacks, etc. connection.StartConnect(); ``` -------------------------------- ### AddNegotiation Source: https://github.com/benedicht/com.tivadar.best.documentation/blob/main/docs/WebSockets/api-reference/Extensions/PerMessageCompression.md Starts the permessage-deflate negotiation process. ```APIDOC ## AddNegotiation ### Description This method initiates the permessage-deflate negotiation process for the WebSocket connection. ### Method Void AddNegotiation(HTTPRequest) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response Void (no return value) #### Response Example None ``` -------------------------------- ### SetupRequest Method Source: https://github.com/benedicht/com.tivadar.best.documentation/blob/main/docs/HTTP/api-reference/Settings/UploadSettings.md Configures the HTTP request, called on each send, including redirects and retries. ```APIDOC ## SetupRequest ### Description Called every time the request is sent out (redirected or retried). ### Method Void ### Parameters - **request** (HTTPRequest) - Description not provided. - **value** (Boolean) - Description not provided. ``` -------------------------------- ### Create MQTT Client with Builder Source: https://github.com/benedicht/com.tivadar.best.documentation/blob/main/docs/MQTT/getting-started/index.md Use the MQTTClientBuilder for a concise way to configure connection options and event handlers before creating the client instance. ```csharp client = new MQTTClientBuilder() .WithOptions(new ConnectionOptionsBuilder().WithTCP("broker.emqx.io", 1883)) .WithEventHandler(OnStateChanged) .WithEventHandler(OnDisconnected) .WithEventHandler(OnError) .CreateClient(); ``` -------------------------------- ### Instantiate WebSocket Source: https://github.com/benedicht/com.tivadar.best.documentation/blob/main/docs/WebSockets/getting-started/index.md Create a new WebSocket instance by providing the server URI to the constructor. Use 'wss://' for secure connections and 'ws://' for unsecure ones. ```cs var webSocket = new WebSocket(new Uri("wss://websocketserver/ws")); ``` -------------------------------- ### Setting the Default Retry Policy Source: https://github.com/benedicht/com.tivadar.best.documentation/blob/main/docs/SignalR/getting-started/IRetryPolicy.md Example of how to set the default retry policy for a HubConnection. ```csharp hub = new HubConnection(new Uri("..."), new JsonProtocol(new LitJsonEncoder()), options); hub.ReconnectPolicy = new DefaultRetryPolicy(); ``` -------------------------------- ### Create MQTTClient Instance Source: https://github.com/benedicht/com.tivadar.best.documentation/blob/main/docs/MQTT/getting-started/index.md Instantiates the MQTTClient using the previously created ConnectionOptions. This client will be used to connect to the MQTT broker. ```csharp var client = new MQTTClient(options); ``` -------------------------------- ### Get Connection ID Source: https://github.com/benedicht/com.tivadar.best.documentation/blob/main/docs/Socket.IO/intermediate-topics/index.md Access the global connection ID through the SocketManager's Handshake property. ```csharp var manager = new SocketManager(new Uri("http://localhost:3000")); manager.Socket.On("connect", OnConnected); void OnConnected(SocketManager manager) { Debug.Log(manager.Handshake.Sid); } ``` -------------------------------- ### SetRangeHeader (startByte) Source: https://github.com/benedicht/com.tivadar.best.documentation/blob/main/docs/HTTP/api-reference/HTTP/HTTPRequest.md Sets the Range header to specify a starting byte position for content download. ```APIDOC ## SetRangeHeader ### Description Sets the Range header to download the content from the given byte position. ### Method PUT (conceptual, as this is an SDK method) ### Parameters #### Path Parameters - **startByte** (long) - Required - The starting byte position for the download. ### Remarks See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35 ``` -------------------------------- ### HostKey.From(Uri, ProxySettings) Source: https://github.com/benedicht/com.tivadar.best.documentation/blob/main/docs/HTTP/api-reference/HostSetting/HostKey.md Creates a HostKey instance from a Uri and optional ProxySettings. This allows for manual creation of host keys. ```APIDOC ## HostKey.From(Uri, ProxySettings) ### Description Creates a HostKey instance from a URI and proxy settings. ### Method [HostKey]() HostKey.From([Uri](https://learn.microsoft.com/en-us/dotnet/api/System.Uri), [ProxySettings](../Settings/ProxySettings.md)) ### Parameters * **uri** ([Uri](https://learn.microsoft.com/en-us/dotnet/api/System.Uri)) - The URI of the host. * **proxySettings** ([ProxySettings](../Settings/ProxySettings.md)) - Optional proxy settings for the host. ``` -------------------------------- ### SetupRequest Source: https://github.com/benedicht/com.tivadar.best.documentation/blob/main/docs/HTTP/api-reference/Settings/ProxySettings.md Sets up the HTTP request to be passed through a proxy server. This method configures the request object with the necessary proxy details. ```APIDOC ## SetupRequest ### Description Sets up the HTTP request for passing through a proxy server. ### Method Not applicable (Method signature provided, not an HTTP endpoint) ### Endpoint Not applicable ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **request** (HTTPRequest) - The HTTP request object to be configured for proxy usage. ### Request Example None ### Response #### Success Response - **Void** - This method does not return a value. #### Response Example None ``` -------------------------------- ### Get Socket ID Source: https://github.com/benedicht/com.tivadar.best.documentation/blob/main/docs/Socket.IO/intermediate-topics/index.md Retrieve the per-socket ID either as a parameter in the connect event or later through the socket instance. ```csharp manager = new SocketManager(new Uri("http://localhost:3000"), options); manager.Socket.On(SocketIOEventTypes.Connect, OnConnected); void OnConnected(ConnectResponse resp) { // Method 1: received as parameter Debug.Log("Sid through parameter: " + resp.sid); // Method 2: access through the socket Debug.Log("Sid through socket: " + manager.Socket.Id); } ``` -------------------------------- ### Create HubConnection with Options Source: https://github.com/benedicht/com.tivadar.best.documentation/blob/main/docs/SignalR/getting-started/index.md Initializes a HubConnection with the server URI, a JSON protocol, and custom HubOptions. This allows for more configuration of the connection. ```cs HubOptions options = new HubOptions(); hub = new HubConnection(new Uri("https://server/hub"), new JsonProtocol(new LitJsonEncoder()), options); ``` -------------------------------- ### Using LitJsonEncoder with JsonProtocol Source: https://github.com/benedicht/com.tivadar.best.documentation/blob/main/docs/SignalR/intermediate-topics/encoders.md Instantiates a HubConnection using the default JsonProtocol with the LitJsonEncoder. No additional setup is required for this encoder. ```csharp var hub = new HubConnection(new Uri("https://server/hub"), new JsonProtocol(new LitJsonEncoder())); ``` -------------------------------- ### Setting a Custom Retry Policy Source: https://github.com/benedicht/com.tivadar.best.documentation/blob/main/docs/SignalR/getting-started/IRetryPolicy.md Example of how to set a custom retry policy with specific backoff times for a HubConnection. ```csharp hub = new HubConnection(new Uri(base.sampleSelector.BaseURL + this._path), new JsonProtocol(new LitJsonEncoder()), options); hub.ReconnectPolicy = new DefaultRetryPolicy(new TimeSpan?[] { TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(15), TimeSpan.FromSeconds(45), TimeSpan.FromSeconds(90), null }); ``` -------------------------------- ### HTTPManager.Setup Source: https://github.com/benedicht/com.tivadar.best.documentation/blob/main/docs/HTTP/api-reference/Shared/HTTPManager.md Initializes the HTTPManager with default settings. This method should be called on Unity's main thread before using the HTTP plugin. By default, it is called by HTTPUpdateDelegator. ```APIDOC ## Void HTTPManager.Setup() ### Description Initializes the HTTPManager with default settings. This method should be called on Unity's main thread before using the HTTP plugin. By default it gets called by [HTTPUpdateDelegator](HTTPUpdateDelegator.md). ### Method Void ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response N/A ``` -------------------------------- ### Get HostSettings by HostKey Source: https://github.com/benedicht/com.tivadar.best.documentation/blob/main/docs/HTTP/api-reference/Settings/HostSettingsManager.md Retrieves host settings for the host part of a given HostKey. Returns default settings if not found. ```APIDOC ## Get [HostSettings](HostSettings.md) ### Description Gets [HostSettings](HostSettings.md) for the host part of the specified [HostKey](../HostSetting/HostKey.md). Returns the default settings associated with "*" when not found. ### Method GET ### Endpoint /settings/host/{hostKey} ### Parameters #### Path Parameters - **hostKey** (HostKey) - Required - The HostKey to get settings for. ``` -------------------------------- ### Get HostSettings by HostVariant Source: https://github.com/benedicht/com.tivadar.best.documentation/blob/main/docs/HTTP/api-reference/Settings/HostSettingsManager.md Retrieves host settings for the host part of a given HostVariant. Returns default settings if not found. ```APIDOC ## Get [HostSettings](HostSettings.md) ### Description Gets [HostSettings](HostSettings.md) for the host part of the specified [HostVariant](../HostSetting/HostVariant.md). Returns the default settings associated with "*" when not found. ### Method GET ### Endpoint /settings/host/{hostVariant} ### Parameters #### Path Parameters - **hostVariant** (HostVariant) - Required - The HostVariant to get settings for. ``` -------------------------------- ### Listen for Connection Establishment Source: https://github.com/benedicht/com.tivadar.best.documentation/blob/main/docs/Server-Sent Events/getting-started/index.md Subscribe to the OnOpen event to be notified when the connection is successfully established. ```csharp sse.OnOpen += OnEventSourceOpened; void OnEventSourceOpened(EventSource source) { Debug.log("Connection established!"); } ``` -------------------------------- ### Disable Auto-Connect with SocketOptions Source: https://github.com/benedicht/com.tivadar.best.documentation/blob/main/docs/Socket.IO/getting-started/index.md Configure SocketOptions to disable automatic connection. The connection will only start when the Open() function is explicitly called. ```cs using Best.SocketIO; SocketOptions options = new SocketOptions(); options.AutoConnect = false; var manager = new SocketManager(new Uri("http://localhost:3000"), options); var root = manager.Socket; // AutoConnect is turned off, Open must be called manager.Open(); ``` -------------------------------- ### SetRangeHeader (startByte, endByte) Source: https://github.com/benedicht/com.tivadar.best.documentation/blob/main/docs/HTTP/api-reference/HTTP/HTTPRequest.md Sets the Range header to specify a byte range for content download, from a starting to an ending position. ```APIDOC ## SetRangeHeader ### Description Sets the Range header to download the content from the given byte position to the given last position. ### Method PUT (conceptual, as this is an SDK method) ### Parameters #### Path Parameters - **startByte** (long) - Required - The starting byte position for the download. - **endByte** (long) - Required - The ending byte position for the download. ### Remarks See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35 ``` -------------------------------- ### Configure BlockingDownloadContentStream Source: https://github.com/benedicht/com.tivadar.best.documentation/blob/main/docs/HTTP/getting-started/downloads.md Modify request setup to use BlockingDownloadContentStream for streaming downloads. This factory is called when a new DownloadContentStream instance is needed. ```csharp var request = HTTPRequest.CreateGet("https://server/path/to/large/resource", OnRequestFinishedCallack); request.DownloadSettings.OnDownloadStarted += OnDownloadStarted; request.DownloadSettings.DownloadStreamFactory = (req, resp, bufferAvailableHandler) => new BlockingDownloadContentStream(resp, req.DownloadSettings.ContentStreamMaxBuffered, bufferAvailableHandler); request.Send(); ``` -------------------------------- ### Setting Subscription Acknowledgment Mode Source: https://github.com/benedicht/com.tivadar.best.documentation/blob/main/docs/STOMP/getting-started/acknowledgmentmodes.md Configure the acknowledgment mode for a STOMP subscription using the SubscriptionBuilder. This example sets the mode to ClientIndividual. ```csharp client.CreateSubscriptionBuilder("/queue/test") .WithAcknowledgmentMode(AcknowledgmentModes.ClientIndividual) .WithCallback(OnTestQueueCallback) .WithAcknowledgmentCallback(OnSubscriptionAck) .BeginSubscribe(); ``` -------------------------------- ### Create New Source: https://github.com/benedicht/com.tivadar.best.documentation/blob/main/docs/Shared/proxy/proxy-autodetect.md Restart proxy detection by assigning a new ProxyDetector instance. This will reinitialize the detector with its default settings. ```cs HTTPManager.ProxyDetector = new ProxyDetector(); ``` -------------------------------- ### Start Connection with ConnectAsync Source: https://github.com/benedicht/com.tivadar.best.documentation/blob/main/docs/SignalR/getting-started/index.md Establishes the SignalR connection asynchronously using ConnectAsync. A log message is displayed upon successful connection. ```cs var hub = new HubConnection(new Uri("https://server/hub"), new JsonProtocol(new JsonProtocol(new LitJsonEncoder()))); await hub.ConnectAsync(); Debug.Log("Connected!"); ``` -------------------------------- ### HubConnection Methods Source: https://github.com/benedicht/com.tivadar.best.documentation/blob/main/docs/SignalR/api-reference/SignalR/HubConnection.md Provides methods for managing the SignalR connection lifecycle, including starting and closing connections, and invoking server-side methods. ```APIDOC ## HubConnection Methods ### Void StartConnect() : Initiates the connection process to the Hub. ### Task ConnectAsync() : Initiates an asynchronous connection to the Hub and returns a task representing the operation. ### Void StartClose() : Begins the process to gracefully close the connection. ### Task CloseAsync() : Initiates an asynchronous close operation for the connection and returns a task representing the operation. ### Send(String, Object[]) : Invokes the specified method on the server without expecting a return value. ### SendAsync(String, Object[]) : Invokes the specified method on the server without expecting a return value. ### SendAsync(String, CancellationToken, Object[]) : Invokes the specified method on the server without expecting a return value, with an option to cancel. ### Void On(String, Action) : Registers a callback to be invoked when the server calls the specified method with no parameters. ### Void Remove(String) : Remove all event handlers for that subscribed with an On call. ``` -------------------------------- ### SetupRequest Source: https://github.com/benedicht/com.tivadar.best.documentation/blob/main/docs/HTTP/api-reference/Authenticators/IAuthenticator.md Sets required headers or content for an HTTP request before it is sent. This method is called every time the request is redirected or retried. ```APIDOC ## SetupRequest ### Description Sets required headers or content for an HTTP request before it is sent. This method is called every time the request is redirected or retried. ### Method (Implicitly called by the HTTP client) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (Void) This method does not return a value. #### Response Example None ``` -------------------------------- ### Get Cookies using CookieJar Source: https://github.com/benedicht/com.tivadar.best.documentation/blob/main/docs/HTTP/upgrade-guide.md Acquire cookies for a specific URI using CookieJar.Get. Received cookies are no longer stored per HttpRespones. ```csharp CookieJar.Get(Uri uri) ``` -------------------------------- ### Namespace Update for TLS Security Source: https://github.com/benedicht/com.tivadar.best.documentation/blob/main/docs/TLS Security/upgrade-guide.md Shows the change in namespace usage for TLS Security setup. Use this when migrating from older versions to v3.x. ```csharp using BestHTTP.Addons.TLSSecurity; TLSSecurity.Setup(); ``` ```csharp using Best.TLSSecurity; TLSSecurity.Setup(); ``` -------------------------------- ### SetupRequest Source: https://github.com/benedicht/com.tivadar.best.documentation/blob/main/docs/HTTP/api-reference/Authenticators/CredentialAuthenticator.md Sets up the required headers for the HTTP request based on the provided credentials. This method is part of the CredentialAuthenticator's functionality for preparing outgoing HTTP requests. ```APIDOC ## Void SetupRequest([HTTPRequest](../HTTP/HTTPRequest.md)) ### Description Sets up the required headers for the HTTP request based on the provided credentials. ### Method Void ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response None #### Response Example None ```