### Install Dependencies for Integration Tests Source: https://github.com/doghappy/socket.io-client-csharp/blob/master/README.md Run this command to install all necessary dependencies for the integration tests. This only needs to be done once. ```bash cd socket.io-client-csharp/tests/socket.io npm run install-all ``` -------------------------------- ### Start Socket.IO Server for Integration Tests Source: https://github.com/doghappy/socket.io-client-csharp/blob/master/README.md Execute this command to start the socket.io server, which is required for running integration tests locally. ```bash npm run start ``` -------------------------------- ### Install Socket.IO Client C# Package Source: https://github.com/doghappy/socket.io-client-csharp/blob/master/_autodocs/GUIDE.md Use this command to add the main Socket.IO Client C# package to your project. ```bash dotnet add package SocketIOClient ``` -------------------------------- ### Install Newtonsoft.Json Serializer Package Source: https://github.com/doghappy/socket.io-client-csharp/blob/master/_autodocs/GUIDE.md Install this optional package if you intend to use the Newtonsoft.Json serializer with the Socket.IO Client C# library. ```bash dotnet add package SocketIOClient.Serializer.NewtonsoftJson ``` -------------------------------- ### Access Configuration Options Source: https://github.com/doghappy/socket.io-client-csharp/blob/master/_autodocs/api-reference/SocketIO.md Gets the configuration options for this client instance. ```csharp public SocketIOOptions Options { get; } ``` -------------------------------- ### Configure Newtonsoft.Json Serializer Options Source: https://github.com/doghappy/socket.io-client-csharp/wiki/Home Integrate Newtonsoft.Json by installing the appropriate dependency and providing custom JsonSerializerSettings via OptionsProvider. This example sets a CamelCaseNamingStrategy. ```csharp var jsonSerializer = new NewtonsoftJsonSerializer(); jsonSerializer.OptionsProvider = () => new JsonSerializerSettings { ContractResolver = new DefaultContractResolver { NamingStrategy = new CamelCaseNamingStrategy() } }; socket.JsonSerializer = jsonSerializer; ``` -------------------------------- ### Complete SocketIOOptions Configuration Source: https://github.com/doghappy/socket.io-client-csharp/blob/master/_autodocs/api-reference/SocketIOOptions.md A comprehensive example showing how to configure various SocketIOOptions, including Engine.IO version, path, reconnection settings, query parameters, extra headers, transport, and authentication. ```csharp var options = new SocketIOOptions { EIO = EngineIO.V4, Path = "/socket.io/", Reconnection = true, ReconnectionAttempts = 10, ReconnectionDelayMax = 5000, ConnectionTimeout = TimeSpan.FromSeconds(30), Query = new NameValueCollection { ["userId"] = "12345", ["version"] = "1.0" }, ExtraHeaders = new Dictionary { ["Authorization"] = "Bearer token123", ["User-Agent"] = "MyApp/1.0" }, Transport = TransportProtocol.Polling, AutoUpgrade = true, Auth = new { token = "auth-token", role = "user" } }; var client = new SocketIO(new Uri("http://localhost:3000"), options); await client.ConnectAsync(); ``` -------------------------------- ### Setting Auth with a String Token Source: https://github.com/doghappy/socket.io-client-csharp/blob/master/_autodocs/api-reference/SocketIOOptions.md Example of setting the Auth property with a simple string token. ```csharp var options = new SocketIOOptions { Auth = "jwt-token-here" }; ``` -------------------------------- ### SocketIO Constructor (Uri, SocketIOOptions, Action?) Source: https://github.com/doghappy/socket.io-client-csharp/blob/master/_autodocs/api-reference/SocketIO.md Creates a Socket.IO client with fully customizable options, including the server URI, specific SocketIOOptions, and an optional delegate for configuring dependency injection services. This is the most flexible constructor for advanced setups. ```APIDOC ## SocketIO(Uri, SocketIOOptions, Action?) ### Description Creates a Socket.IO client with custom options and optional dependency injection configuration. ### Method Constructor ### Parameters #### Path Parameters - **uri** (Uri) - Yes - The Socket.IO server endpoint - **options** (SocketIOOptions) - Yes - Configuration options for the client - **configure** (Action?) - No - Custom service registration delegate for dependency injection ### Remarks - This is the primary constructor supporting full customization - All other constructor overloads delegate to this one - The `configure` parameter allows adding custom serializers, HTTP handlers, and logging ### Example ```csharp var client = new SocketIO( new Uri("http://localhost:3000"), new SocketIOOptions { Reconnection = true, ReconnectionAttempts = 5, Transport = TransportProtocol.WebSocket }, services => { services.AddLogging(builder => { builder.SetMinimumLevel(LogLevel.Debug); builder.AddConsole(); }); } ); ``` ``` -------------------------------- ### Use Custom Serializer Source: https://github.com/doghappy/socket.io-client-csharp/blob/master/_autodocs/README.md Provides examples for configuring a custom serializer for event data. ```APIDOC ## Custom Serializer Configuration ### Description Provides examples for configuring a custom serializer to handle event data serialization and deserialization. ### Usage Refer to the `Serializers.md` file for detailed configuration examples. ``` -------------------------------- ### Configure ClientWebSocket Options with Proxy and Headers Source: https://github.com/doghappy/socket.io-client-csharp/wiki/Home Customize the WebSocket client by providing a custom ClientWebSocketProvider. This example demonstrates setting a WebProxy, request headers, and a custom RemoteCertificateValidationCallback. ```csharp var client = new SocketIO("http://localhost:11000/"); client.ClientWebSocketProvider = () => { var clientWebSocket = new DefaultClientWebSocket { ConfigOptions = o => { var options = o as ClientWebSocketOptions; var proxy = new WebProxy("http://example.com"); proxy.Credentials = new NetworkCredential("username", "password"); options.Proxy = proxy; options.SetRequestHeader("key", "value"); options.RemoteCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => { Console.WriteLine("SslPolicyErrors: " + sslPolicyErrors); if (sslPolicyErrors == System.Net.Security.SslPolicyErrors.None) { return true; } return true; }; } }; return clientWebSocket; }; ``` -------------------------------- ### Server-side Ack Example in JavaScript Source: https://github.com/doghappy/socket.io-client-csharp/wiki/Home Illustrates how a server-side JavaScript function can receive data and an acknowledgment callback, then execute the callback with a response. ```js socket.on("ack", (name, fn) => { fn({ result: true, message: `${name} - server` }); }); ``` -------------------------------- ### Configure Newtonsoft.Json Serializer Source: https://github.com/doghappy/socket.io-client-csharp/blob/master/README.md Install the SocketIOClient.Serializer.NewtonsoftJson package and use this snippet to configure Newtonsoft.Json with custom JsonSerializerSettings. ```csharp var client = new SocketIO(new Uri("http://localhost:11400"), services => { services.AddNewtonsoftJson(new JsonSerializerSettings()); }); ``` -------------------------------- ### Server-side Ack2 Example in JavaScript Source: https://github.com/doghappy/socket.io-client-csharp/wiki/Home Demonstrates a server-side JavaScript function that receives multiple arguments and an acknowledgment callback, then calls the callback with swapped arguments. ```js socket.emit("ack2", 1, 2, (arg1, arg2) => { console.log(`arg1: ${arg1}, arg2: ${arg2}`); }); ``` -------------------------------- ### Enable Windows 7 Support with ClientWebSocketManaged Source: https://github.com/doghappy/socket.io-client-csharp/wiki/Home For Windows 7 compatibility, install the SocketIOClient.Windows7 dependency and set the ClientWebSocketProvider to use ClientWebSocketManaged. ```csharp client.ClientWebSocketProvider = () => new ClientWebSocketManaged(); ``` -------------------------------- ### SocketIO Constructor (Uri) Source: https://github.com/doghappy/socket.io-client-csharp/blob/master/_autodocs/api-reference/SocketIO.md Creates a Socket.IO client instance using the provided URI and default options. This constructor is suitable for basic connections where default configurations for reconnection, transport, and service setup are acceptable. ```APIDOC ## SocketIO(Uri) ### Description Creates a Socket.IO client with default options and URI. ### Method Constructor ### Parameters #### Path Parameters - **uri** (Uri) - Yes - The Socket.IO server endpoint (e.g., `http://localhost:3000` or `http://localhost:3000/socket`) ### Remarks - Uses default `SocketIOOptions` - No custom service configuration - Transport defaults to HTTP Polling with automatic upgrade to WebSocket ### Example ```csharp var client = new SocketIO(new Uri("http://localhost:3000")); await client.ConnectAsync(); ``` ``` -------------------------------- ### Setting Auth with an Anonymous Object Source: https://github.com/doghappy/socket.io-client-csharp/blob/master/_autodocs/api-reference/SocketIOOptions.md Example of setting the Auth property with an anonymous object containing token and userId. ```csharp var options = new SocketIOOptions { Auth = new { token = "jwt-token-here", userId = 42 } }; ``` -------------------------------- ### Binary Data Handling with Custom Attributes Source: https://github.com/doghappy/socket.io-client-csharp/blob/master/_autodocs/api-reference/Serializers.md Handle binary data (byte arrays) in JSON objects using custom property attributes. This example demonstrates sending and receiving file data. ```csharp public class FileData { [JsonPropertyName("name")] public string Name { get; set; } [JsonPropertyName("content")] public byte[] Content { get; set; } } // Send: var file = new FileData { Name = "document.pdf", Content = File.ReadAllBytes("document.pdf") }; await client.EmitAsync("upload-file", new[] { file }); // Receive: client.On("file-received", ctx => { var received = ctx.GetValue(0); File.WriteAllBytes(received.Name, received.Content); return Task.CompletedTask; }); ``` -------------------------------- ### SocketIO Client Creation with Options Source: https://github.com/doghappy/socket.io-client-csharp/blob/master/_autodocs/api-reference/ISocketIO.md Demonstrates how to create a new SocketIO client instance with custom options, specifically enabling reconnection. ```csharp var client = new SocketIO(uri, new SocketIOOptions { Reconnection = true }); Console.WriteLine($ ``` ```csharp client.OnConnected += (sender, args) => { Console.WriteLine($"My Socket ID: {client.Id}"); }; ``` ```csharp if (!client.Connected) { await client.ConnectAsync(); } // Now safe to emit await client.EmitAsync("message", new[] { "Hello" }); ``` -------------------------------- ### Connect and Listen to Events in C# Source: https://github.com/doghappy/socket.io-client-csharp/wiki/Home Establishes a connection to a Socket.IO server and sets up listeners for 'hi' and 'test' events. Handles incoming data and demonstrates how to retrieve specific values from the response. ```cs var client = new SocketIO("http://localhost:11000/"); client.On("hi", response => { // You can print the returned data first to decide what to do next. // output: ["hi client"] Console.WriteLine(response); string text = response.GetValue(); // The socket.io server code looks like this: // socket.emit('hi', 'hi client'); }); client.On("test", response => { // You can print the returned data first to decide what to do next. // output: ["ok",{"id":1,"name":"tom"}] Console.WriteLine(response); // Get the first data in the response string text = response.GetValue(); // Get the second data in the response var dto = response.GetValue(1); // The socket.io server code looks like this: // socket.emit('hi', 'ok', { id: 1, name: 'tom'}); }); client.OnConnected += async (sender, e) => { // Emit a string await client.EmitAsync("hi", "socket.io"); // Emit a string and an object var dto = new TestDTO { Id = 123, Name = "bob" }; await client.EmitAsync("register", "source", dto); }; await client.ConnectAsync(); ``` -------------------------------- ### Get Session Identifier Source: https://github.com/doghappy/socket.io-client-csharp/blob/master/_autodocs/api-reference/SocketIO.md Gets the Socket.IO session identifier, assigned by the server upon successful connection. This property is null until the client connects and is cleared upon disconnection. ```csharp public string? Id { get; } ``` -------------------------------- ### Configure Logging Source: https://github.com/doghappy/socket.io-client-csharp/blob/master/_autodocs/GUIDE.md Set up logging for the client connection, including minimum log level and console output. ```csharp var client = new SocketIO( new Uri("http://localhost:3000"), services => { services.AddLogging(builder => { builder.SetMinimumLevel(LogLevel.Debug); builder.AddConsole(); }); } ); ``` -------------------------------- ### Check Connection Status Source: https://github.com/doghappy/socket.io-client-csharp/blob/master/_autodocs/api-reference/SocketIO.md Gets a value indicating whether the client is currently connected to the server. ```csharp public bool Connected { get; } ``` -------------------------------- ### Configure Socket.IO Client Options in C# Source: https://github.com/doghappy/socket.io-client-csharp/wiki/Home Demonstrates how to customize Socket.IO client connection options, such as adding query parameters for authentication or identification. ```cs var client = new SocketIO("http://localhost:11000/", new SocketIOOptions { Query = new List> { new KeyValuePair("token", "abc123"), new KeyValuePair("key", "value") } }); ``` -------------------------------- ### Combined Custom Configuration Source: https://github.com/doghappy/socket.io-client-csharp/blob/master/_autodocs/configuration.md Demonstrates combining multiple custom configurations including Socket.IO options, JSON serialization, HTTP client, WebSocket options, and logging. ```csharp var client = new SocketIO( new Uri("https://api.example.com/socket"), new SocketIOOptions { EIO = EngineIO.V4, Path = "/api/socket.io/", Reconnection = true, ReconnectionAttempts = 15, ReconnectionDelayMax = 5000, ConnectionTimeout = TimeSpan.FromSeconds(20), Transport = TransportProtocol.Polling, AutoUpgrade = true, Query = new NameValueCollection { ["token"] = "abc123" }, ExtraHeaders = new Dictionary { ["Authorization"] = "Bearer xyz789" }, Auth = new { userId = 42 } }, services => { // Custom JSON options services.AddSystemTextJson(new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase }); // Custom HTTP client for polling services.AddSingleton(provider => { var handler = new HttpClientHandler { Proxy = new WebProxy("http://internal-proxy:3128") }; return new HttpClient(handler); }); // WebSocket options services.AddSingleton(new WebSocketOptions { RemoteCertificateValidationCallback = ValidateCertificate }); // Logging services.AddLogging(builder => { builder.SetMinimumLevel(LogLevel.Debug); builder.AddConsole(); }); } ); static bool ValidateCertificate(object sender, X509Certificate2 cert, X509Chain chain, SslPolicyErrors errors) { // Custom validation logic return true; } ``` -------------------------------- ### Connect to Socket.IO Server Source: https://github.com/doghappy/socket.io-client-csharp/blob/master/_autodocs/README.md Establishes a connection to a Socket.IO server. Ensure the server is running at the specified URI. ```csharp var client = new SocketIO(new Uri("http://localhost:3000")); await client.ConnectAsync(); ``` -------------------------------- ### Get OnAny Handler Count Source: https://github.com/doghappy/socket.io-client-csharp/blob/master/_autodocs/api-reference/ISocketIO.md Retrieves the number of registered OnAny handlers. Useful for debugging or introspection. ```csharp var handlerCount = client.ListenersAny.Count(); Console.WriteLine($"Registered {handlerCount} OnAny handlers"); ``` -------------------------------- ### Connect to a Server Source: https://github.com/doghappy/socket.io-client-csharp/blob/master/_autodocs/README.md Establishes a connection to the Socket.IO server. ```APIDOC ## ConnectAsync() ### Description Establishes a connection to the Socket.IO server. ### Method `ConnectAsync()` ``` -------------------------------- ### ConnectionTimeout Property Source: https://github.com/doghappy/socket.io-client-csharp/blob/master/_autodocs/api-reference/SocketIOOptions.md Gets or sets the maximum duration to wait for a connection to be established. This applies to each individual connection attempt. ```APIDOC ## ConnectionTimeout ### Description Gets or sets the maximum duration to wait for a connection to be established. This timeout applies to each individual connection attempt. ### Property - **ConnectionTimeout** (`TimeSpan`) - Required - Time to wait before timing out a connection attempt (default: 30 seconds) ### Remarks - Applies to each individual connection attempt. - If reconnection is enabled, each attempt gets this timeout. - Total time for all attempts = `ConnectionTimeout` × `ReconnectionAttempts` + delays between attempts. - A `TimeoutException` is thrown if exceeded. ### Example ```csharp var options = new SocketIOOptions { ConnectionTimeout = TimeSpan.FromSeconds(15) }; ``` ``` -------------------------------- ### Complete Connection with Error Handling Source: https://github.com/doghappy/socket.io-client-csharp/blob/master/_autodocs/errors.md Demonstrates a comprehensive approach to connecting, including setting reconnection options and handling various connection-related exceptions like ConnectionException, TimeoutException, and TaskCanceledException. ```csharp var client = new SocketIO(new Uri("http://localhost:3000"), new SocketIOOptions { Reconnection = true, ReconnectionAttempts = 5, ConnectionTimeout = TimeSpan.FromSeconds(10) }); client.OnReconnectAttempt += (sender, attempt) => { Console.WriteLine($"Reconnection attempt {attempt}"); }; client.OnReconnectError += (sender, ex) => { Console.WriteLine($"Reconnection error: {ex.Message}"); }; client.OnError += (sender, error) => { Console.WriteLine($"Server error: {error}"); }; try { await client.ConnectAsync(); Console.WriteLine("Connected successfully"); } catch (ConnectionException ex) { Console.WriteLine($"Connection failed after all attempts: {ex.Message}"); } catch (TimeoutException ex) { Console.WriteLine("Connection timed out"); } catch (TaskCanceledException ex) { Console.WriteLine("Connection was cancelled"); } ``` -------------------------------- ### ReconnectionAttempts Property Source: https://github.com/doghappy/socket.io-client-csharp/blob/master/_autodocs/api-reference/SocketIOOptions.md Gets or sets the maximum number of connection attempts before giving up. This property is only used if Reconnection is set to true. ```APIDOC ## ReconnectionAttempts ### Description Gets or sets the maximum number of connection attempts before giving up. This property is only used if `Reconnection` is set to `true`. ### Property - **ReconnectionAttempts** (`int`) - Required - Number of attempts before giving up (default: 10, Valid Range: ≥ 1) ### Throws - `ArgumentException` — Value is less than 1 ### Remarks - Only used if `Reconnection` is `true`. - Each attempt waits up to `ConnectionTimeout` for a response. - Between attempts, a random delay (0 to `ReconnectionDelayMax` milliseconds) is applied. - Setting to 1 means only one attempt (no retries). ### Example ```csharp var options = new SocketIOOptions { ReconnectionAttempts = 5 }; ``` ``` -------------------------------- ### ISerializer Namespace Property Source: https://github.com/doghappy/socket.io-client-csharp/blob/master/_autodocs/api-reference/Serializers.md Represents the Socket.IO namespace for routing protocol messages. It is typically set during client connection setup. ```csharp string? Namespace { get; set; } ``` -------------------------------- ### Connect to Standard Socket.IO 3.x/4.x Server Source: https://github.com/doghappy/socket.io-client-csharp/blob/master/_autodocs/GUIDE.md Use this snippet to establish a connection to a standard Socket.IO 3.x or 4.x server. ```csharp var client = new SocketIO(new Uri("http://localhost:3000")); ``` -------------------------------- ### Create SocketIOOptions with Defaults Source: https://github.com/doghappy/socket.io-client-csharp/blob/master/_autodocs/api-reference/SocketIOOptions.md Instantiate SocketIOOptions to use default settings for connection and client behavior. ```csharp var options = new SocketIOOptions(); var client = new SocketIO(new Uri("http://localhost:3000"), options); ``` -------------------------------- ### Force WebSocket-Only Connection Source: https://github.com/doghappy/socket.io-client-csharp/blob/master/_autodocs/configuration.md Use this when the server only supports WebSocket or when you want to ensure the lowest latency from the start. It disables fallback to polling. ```csharp var client = new SocketIO(new Uri("http://localhost:3000"), new SocketIOOptions { Transport = TransportProtocol.WebSocket, AutoUpgrade = false }); ``` -------------------------------- ### ReconnectionDelayMax Property Source: https://github.com/doghappy/socket.io-client-csharp/blob/master/_autodocs/api-reference/SocketIOOptions.md Gets or sets the maximum random delay in milliseconds between reconnection attempts. This helps prevent thundering herd scenarios. ```APIDOC ## ReconnectionDelayMax ### Description Gets or sets the maximum random delay (in milliseconds) between reconnection attempts. This helps prevent thundering herd scenarios when multiple clients reconnect simultaneously. ### Property - **ReconnectionDelayMax** (`int`) - Required - Maximum milliseconds to wait between attempts (default: 5000) ### Remarks - Actual delay between attempts is a random value: 0 to `ReconnectionDelayMax` milliseconds. - Helps prevent thundering herd scenarios when multiple clients reconnect simultaneously. - Only applicable if `Reconnection` is `true` and a retry is needed. - Does not affect the timeout for individual attempts (see `ConnectionTimeout`). ### Example ```csharp var options = new SocketIOOptions { ReconnectionDelayMax = 10000 }; // Up to 10 seconds ``` ``` -------------------------------- ### EIO Property Source: https://github.com/doghappy/socket.io-client-csharp/blob/master/_autodocs/api-reference/SocketIOOptions.md Gets or sets the Engine.IO protocol version to use for the connection. This must match the server's supported version. ```APIDOC ## EIO ### Description Gets or sets the Engine.IO protocol version to use. This setting is crucial for compatibility with the Socket.IO server. ### Property - **EIO** (`EngineIO`) - Required - Engine.IO protocol version: V3 (for Socket.IO 2.x) or V4 (for Socket.IO 3.x/4.x) (default: `EngineIO.V4`) ### Values - `EngineIO.V3` — For Socket.IO server 2.x - `EngineIO.V4` — For Socket.IO server 3.x and 4.x (default) ### Remarks - Must match the protocol version supported by the server. - Mismatch will result in connection failures. - V3 is for legacy Socket.IO 2.x servers only. ### Example ```csharp var options = new SocketIOOptions { EIO = EngineIO.V3 }; // For Socket.IO 2.x ``` ``` -------------------------------- ### Configure Socket.IO Client Options Source: https://github.com/doghappy/socket.io-client-csharp/blob/master/_autodocs/README.md Initializes a Socket.IO client with custom options, including enabling reconnection, setting reconnection attempts, specifying the transport protocol, and enabling automatic upgrades. ```csharp var client = new SocketIO( new Uri("http://localhost:3000"), new SocketIOOptions { Reconnection = true, ReconnectionAttempts = 10, Transport = TransportProtocol.Polling, AutoUpgrade = true } ); ``` -------------------------------- ### SocketIO Constructor (Uri, Action) Source: https://github.com/doghappy/socket.io-client-csharp/blob/master/_autodocs/api-reference/SocketIO.md Creates a Socket.IO client using the provided URI and default options, while allowing custom service registration through a delegate. This is useful for injecting custom services like serializers or logging without altering the core SocketIOOptions. ```APIDOC ## SocketIO(Uri, Action) ### Description Creates a Socket.IO client with default options and custom service configuration. ### Method Constructor ### Parameters #### Path Parameters - **uri** (Uri) - Yes - The Socket.IO server endpoint - **configure** (Action) - Yes - Custom service registration delegate ### Example ```csharp var client = new SocketIO(new Uri("http://localhost:3000"), services => { services.AddNewtonsoftJson(new JsonSerializerSettings()); }); ``` ``` -------------------------------- ### Create SocketIO Client with Default Options and DI Configuration Source: https://github.com/doghappy/socket.io-client-csharp/blob/master/_autodocs/api-reference/SocketIO.md Use this constructor when you need to configure dependency injection services while using the default Socket.IO client options. This is suitable for scenarios where you want to add custom serializers or other services without altering the default connection behavior. ```csharp var client = new SocketIO(new Uri("http://localhost:3000"), services => { services.AddNewtonsoftJson(new JsonSerializerSettings()); }); ``` -------------------------------- ### Reconnection Property Source: https://github.com/doghappy/socket.io-client-csharp/blob/master/_autodocs/api-reference/SocketIOOptions.md Gets or sets whether the client automatically retries failed connections. If true, connection failures trigger automatic retries up to ReconnectionAttempts. ```APIDOC ## Reconnection ### Description Gets or sets whether the client automatically retries failed connections. When enabled, connection failures trigger automatic retries. ### Property - **Reconnection** (`bool`) - Required - Enable automatic reconnection on connection failure (default: `true`) ### Remarks - When `true`, connection failures trigger automatic retries up to `ReconnectionAttempts` times. - When `false`, the first connection failure immediately throws an exception. - Automatic reconnection does not occur after client-initiated disconnect via `DisconnectAsync()`. - If `Reconnection` is `true` but `ReconnectionAttempts` is 1, only one attempt is made. ### Example ```csharp var options = new SocketIOOptions { Reconnection = false }; // No retry ``` ``` -------------------------------- ### Custom Socket.IO Client Options Source: https://github.com/doghappy/socket.io-client-csharp/blob/master/README.md Use this overload to provide custom configuration for the Socket.IO client, such as setting query parameters for the initial connection. ```csharp var client = new SocketIO(new Uri("http://localhost:11400"), new SocketIOOptions { Query = new NameValueCollection { ["user"] = "Alice" }, // ... }); ``` -------------------------------- ### Programmatic Configuration with Environment Variables Source: https://github.com/doghappy/socket.io-client-csharp/blob/master/_autodocs/configuration.md Configure the Socket.IO client programmatically by reading environment variables for the server URL and authentication token. Defaults are provided if environment variables are not set. ```csharp var serverUrl = Environment.GetEnvironmentVariable("SOCKET_IO_URL") ?? "http://localhost:3000"; var token = Environment.GetEnvironmentVariable("SOCKET_IO_TOKEN"); var client = new SocketIO(new Uri(serverUrl), new SocketIOOptions { Auth = new { token = token } }); ``` -------------------------------- ### RawText Property Source: https://github.com/doghappy/socket.io-client-csharp/blob/master/_autodocs/api-reference/IEventContext.md Gets the raw Socket.IO protocol message text. This property provides access to the complete, unparsed message string, which can be useful for debugging or advanced logging scenarios. ```APIDOC ## RawText Property ### Description Gets the raw Socket.IO protocol message text. This property provides access to the complete, unparsed message string, which can be useful for debugging or advanced logging scenarios. ### Property Signature ```csharp string RawText { get; } ``` ### Properties - **RawText** (`string`) - Readable ### Remarks - Contains the complete raw message including event name and all data elements. - Formatted as a JSON array: `["eventName", data1, data2, ...]`. - Useful for debugging or logging the exact protocol message. - For advanced use cases where structured parsing is not sufficient. ### Example ```csharp client.On("debug-event", ctx => { Console.WriteLine($"Raw message: {ctx.RawText}"); // Output: ["my-event", "data1", 42, {"key":"value"}] return Task.CompletedTask; }); ``` ``` -------------------------------- ### Basic Socket.IO Client Connection Source: https://github.com/doghappy/socket.io-client-csharp/blob/master/_autodocs/GUIDE.md Establishes a basic connection to a Socket.IO server, registers a message handler, emits a message, and disconnects. Ensure the server URI is correct. ```csharp using SocketIOClient; var client = new SocketIO(new Uri("http://localhost:3000")); client.On("message", ctx => { var text = ctx.GetValue(0); Console.WriteLine($"Message: {text}"); return Task.CompletedTask; }); await client.ConnectAsync(); await client.EmitAsync("message", new object[] { "Hello, Server!" }); await client.DisconnectAsync(); ``` -------------------------------- ### Connect to Socket.IO Server Source: https://github.com/doghappy/socket.io-client-csharp/blob/master/_autodocs/GUIDE.md Connect to the server using default options or with a cancellation token for a timeout. ```csharp // Connect with defaults await client.ConnectAsync(); // Connect with cancellation using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(30)); await client.ConnectAsync(cts.Token); ``` -------------------------------- ### Listen for and Emit Messages Source: https://github.com/doghappy/socket.io-client-csharp/blob/master/_autodocs/README.md Sets up a listener for incoming 'message' events and emits a 'message' event with data. The listener handles string data and returns a completed task. ```csharp client.On("message", ctx => { var text = ctx.GetValue(0); Console.WriteLine($"Message: {text}"); return Task.CompletedTask; }); await client.EmitAsync("message", new[] { "Hello!" }); ``` -------------------------------- ### Configure Client Options Source: https://github.com/doghappy/socket.io-client-csharp/blob/master/_autodocs/README.md Configures the Socket.IO client using various options. ```APIDOC ## SocketIOOptions ### Description Provides a comprehensive table of configuration options for the Socket.IO client, including protocol version, timeouts, reconnection settings, and more. ### Options | Option | Default | Type | Purpose | |---|---|---|---| | `EIO` | V4 | `EngineIO` | Protocol version | | `ConnectionTimeout` | 30s | `TimeSpan` | Connection attempt timeout | | `Reconnection` | true | `bool` | Enable auto-reconnect | | `ReconnectionAttempts` | 10 | `int` | Max reconnection attempts | | `ReconnectionDelayMax` | 5000ms | `int` | Max delay between attempts | | `Path` | `/socket.io/` | `string?` | Service endpoint path | | `Query` | null | `NameValueCollection?` | Handshake query params | | `ExtraHeaders` | null | `IReadOnlyDictionary?` | HTTP headers for polling | | `Auth` | null | `object?` | Authentication data | | `Transport` | Polling | `TransportProtocol` | Initial transport | | `AutoUpgrade` | true | `bool` | Upgrade to WebSocket | ``` -------------------------------- ### Configure System.Text.Json with Custom Options Source: https://github.com/doghappy/socket.io-client-csharp/blob/master/_autodocs/api-reference/Serializers.md Demonstrates how to configure the Socket.IO client to use System.Text.Json with custom JsonSerializerOptions, including property naming policies and enum conversion. ```csharp using System.Text.Json; using System.Text.Json.Serialization; using Microsoft.Extensions.DependencyInjection; using SocketIOClient; var options = new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase, PropertyNameCaseInsensitive = true, DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull, Converters = { new JsonStringEnumConverter() } }; var client = new SocketIO( new Uri("http://localhost:3000"), new SocketIOOptions { EIO = EngineIO.V4 }, services => { services.AddSystemTextJson(options); } ); await client.ConnectAsync(); // Use the client client.On("message", ctx => { var text = ctx.GetValue(0); Console.WriteLine(text); return Task.CompletedTask; }); ``` -------------------------------- ### Handling ConnectionException in C# Source: https://github.com/doghappy/socket.io-client-csharp/blob/master/_autodocs/errors.md Demonstrates how to catch and handle ConnectionException during an asynchronous connection attempt. It also shows how to access the inner exception for more details. ```csharp try { await client.ConnectAsync(); } catch (ConnectionException ex) { Console.WriteLine($"Connection failed: {ex.Message}"); if (ex.InnerException != null) { Console.WriteLine($"Root cause: {ex.InnerException.GetType().Name}"); } } ``` -------------------------------- ### Listen for New Files Event with Binary Data Source: https://github.com/doghappy/socket.io-client-csharp/blob/master/README.md Listens for the 'new files' event and deserializes the incoming data into a FileDTO object. It then extracts and decodes the byte array to display the file content. ```cs client.On("new files", ctx => { // RawText: ["new files", {"name":"template.html","mimeType":"text/html","bytes":{"_placeholder":true,"num":0}}] var result = ctx.GetValue(); Console.WriteLine(Encoding.UTF8.GetString(result.Bytes)) ``` -------------------------------- ### Listen to Events Source: https://github.com/doghappy/socket.io-client-csharp/blob/master/_autodocs/GUIDE.md Set up listeners for specific events, one-time events, or all events. Listeners can be added or removed. ```csharp // Single listener (replace on each call) client.On("message", ctx => { var text = ctx.GetValue(0); return Task.CompletedTask; }); // One-time listener client.Once("connect", ctx => { Console.WriteLine("Connected!"); return Task.CompletedTask; }); // Listener for all events client.OnAny((eventName, ctx) => { Console.WriteLine($"Event: {eventName}"); return Task.CompletedTask; }); // Remove all-events listener client.OffAny(myHandler); // Prepend listener (runs before OnAny) client.PrependAny((eventName, ctx) => { Console.WriteLine($"[LOG] {eventName}"); return Task.CompletedTask; }); ``` -------------------------------- ### ConnectAsync() Method Signature Source: https://github.com/doghappy/socket.io-client-csharp/blob/master/_autodocs/api-reference/ISocketIO.md Establishes a connection to the Socket.IO server. This method attempts to connect based on configured options and respects reconnection settings. It fires OnConnected event on success and handles various exceptions. ```csharp Task ConnectAsync() ``` -------------------------------- ### Connect and Receive Events with Socket.IO Source: https://github.com/doghappy/socket.io-client-csharp/blob/master/README.md Connect to a Socket.IO server and handle incoming events. The `On` method registers a callback for a specific event. The `ctx` object provides access to the raw event text and parsed data payloads. ```cs var client = new SocketIO(new Uri("http://localhost:11400")); client.On("event", ctx => { // RawText: ["event","Hello World!", 1, {"Name":"Alice","Age":18}] // The first element in the array is the event name, // and the subsequent elements are the data carried with the event. Console.WriteLine(ctx.RawText); // Use index 0 to access the first item in the data payload, which is of type string. var message = ctx.GetValue(0)!; Console.WriteLine(message); // Hello World! // Use index 1 to access the second data item in the payload. The data type is int. var id = ctx.GetValue(1); Console.WriteLine(id); // 1 // Use index 2 to access the third data item in the payload. The data type is User. var user = ctx.GetValue(2)!; Console.WriteLine($"Name: {user.Name}, Age: {user.Age}"); // Name: Alice, Age: 18 return Task.CompletedTask; }); ``` -------------------------------- ### Connect with JWT Authentication Source: https://github.com/doghappy/socket.io-client-csharp/blob/master/_autodocs/GUIDE.md Configure JWT authentication by providing a token in the connection options. ```csharp var client = new SocketIO( new Uri("http://localhost:3000"), new SocketIOOptions { Auth = new { token = "jwt-token-here" } } ); ``` -------------------------------- ### Configure Socket.IO Client for Legacy Socket.IO 2.x Server Source: https://github.com/doghappy/socket.io-client-csharp/blob/master/_autodocs/configuration.md Connect to older Socket.IO 2.x servers that use Engine.IO V3. Specify the Engine.IO version in the options. ```csharp var client = new SocketIO(new Uri("http://localhost:3000"), new SocketIOOptions { EIO = EngineIO.V3 }); ``` -------------------------------- ### Support for Windows 7/2008 R2 Source: https://github.com/doghappy/socket.io-client-csharp/blob/master/CHANGELOG.md Demonstrates how to configure SocketIOClient to support Windows 7 and Windows 2008 R2 by using a plug-in. This is useful when the default WebSocket implementation is not compatible with older Windows versions. ```cs var client = new SocketIO(...); client.Socket = new ClientWebSocketManaged(); ``` -------------------------------- ### SessionOptions Class Source: https://github.com/doghappy/socket.io-client-csharp/blob/master/_autodocs/types.md Configuration options for a session, including server URI, path, namespace, query parameters, and timeouts. Use this to customize connection settings. ```csharp namespace SocketIOClient.Session public class SessionOptions { public Uri ServerUri { get; set; } = null!; public string? Path { get; set; } public string? Namespace { get; set; } public NameValueCollection? Query { get; set; } public TimeSpan Timeout { get; set; } public EngineIO EngineIO { get; set; } public IReadOnlyDictionary? ExtraHeaders { get; set; } public object? Auth { get; set; } public bool AutoUpgrade { get; set; } public string? Sid { get; set; } } ``` -------------------------------- ### Event Listening Source: https://github.com/doghappy/socket.io-client-csharp/blob/master/_autodocs/MANIFEST.txt Methods for registering and managing event listeners. ```APIDOC ## On(eventName, handler) ### Description Registers a handler to be called when a specific event is received. ### Method POST ### Endpoint /on ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **eventName** (string) - Required - The name of the event to listen for. - **handler** (function) - Required - The callback function to execute when the event is received. ### Request Example ```json { "eventName": "chat message", "handler": "handleMessage" } ``` ### Response #### Success Response (200) - **status** (string) - Indicates the listener was registered successfully. #### Response Example ```json { "status": "registered" } ``` ## Once(eventName, handler) ### Description Registers a handler to be called only once when a specific event is received. ### Method POST ### Endpoint /once ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **eventName** (string) - Required - The name of the event to listen for. - **handler** (function) - Required - The callback function to execute when the event is received. ### Request Example ```json { "eventName": "user joined", "handler": "handleUserJoinOnce" } ``` ### Response #### Success Response (200) - **status** (string) - Indicates the listener was registered successfully. #### Response Example ```json { "status": "registered" } ``` ## OnAny(handler) ### Description Registers a handler to be called for any event received. ### Method POST ### Endpoint /onany ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **handler** (function) - Required - The callback function to execute for any event. ### Request Example ```json { "handler": "handleAnyEvent" } ``` ### Response #### Success Response (200) - **status** (string) - Indicates the listener was registered successfully. #### Response Example ```json { "status": "registered" } ``` ## OffAny(handler) ### Description Removes a previously registered handler for any event. ### Method DELETE ### Endpoint /offany ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **handler** (function) - Required - The callback function to remove. ### Request Example ```json { "handler": "handleAnyEvent" } ``` ### Response #### Success Response (200) - **status** (string) - Indicates the listener was removed successfully. #### Response Example ```json { "status": "removed" } ``` ## PrependAny(handler) ### Description Registers a handler to be called for any event received, prepending it to the list of handlers. ### Method POST ### Endpoint /prependany ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **handler** (function) - Required - The callback function to execute for any event. ### Request Example ```json { "handler": "handleAnyEventFirst" } ``` ### Response #### Success Response (200) - **status** (string) - Indicates the listener was registered successfully. #### Response Example ```json { "status": "registered" } ``` ``` -------------------------------- ### Create SocketIO Client with Custom Options and DI Source: https://github.com/doghappy/socket.io-client-csharp/blob/master/_autodocs/api-reference/SocketIO.md This constructor provides full customization for the Socket.IO client. You can specify custom options for reconnection, transport, and more, along with an optional delegate to configure dependency injection services. This is useful for advanced scenarios like custom serializers or logging. ```csharp var client = new SocketIO( new Uri("http://localhost:3000"), new SocketIOOptions { Reconnection = true, ReconnectionAttempts = 5, Transport = TransportProtocol.WebSocket }, services => { services.AddLogging(builder => { builder.SetMinimumLevel(LogLevel.Debug); builder.AddConsole(); }); } ); ``` -------------------------------- ### Middleware-Style Event Processing Source: https://github.com/doghappy/socket.io-client-csharp/blob/master/_autodocs/GUIDE.md Shows how to log all incoming events using OnAny and process specific events like 'user:update'. ```csharp // Log all events client.OnAny(async (eventName, ctx) => { Console.WriteLine($"[{DateTime.UtcNow:O}] {eventName}: {ctx.RawText}"); }); // Process specific events client.On("user:update", ctx => { var user = ctx.GetValue(0); return ProcessUserUpdateAsync(user); }); ``` -------------------------------- ### Socket.IO Client Connection with Configuration Source: https://github.com/doghappy/socket.io-client-csharp/blob/master/_autodocs/GUIDE.md Connects to a Socket.IO server with custom configurations including reconnection attempts, transport protocol, auto-upgrade, and query parameters. Useful for tailoring client behavior to specific server environments. ```csharp var client = new SocketIO( new Uri("http://localhost:3000"), new SocketIOOptions { Reconnection = true, ReconnectionAttempts = 10, Transport = TransportProtocol.Polling, AutoUpgrade = true, Query = new NameValueCollection { ["token"] = "abc123" } } ); await client.ConnectAsync(); ``` -------------------------------- ### Handle Authentication Source: https://github.com/doghappy/socket.io-client-csharp/blob/master/_autodocs/README.md Configures JWT authentication for the client connection. ```APIDOC ## JWT Authentication ### Description Configures JWT authentication for the client connection using the `Auth` option within `SocketIOOptions`. ### Configuration Set the `Auth` property in `SocketIOOptions` to your JWT token or authentication payload. ``` -------------------------------- ### Graceful Shutdown with using statement Source: https://github.com/doghappy/socket.io-client-csharp/blob/master/_autodocs/GUIDE.md Illustrates graceful shutdown using a 'using' statement for automatic disposal of the Socket.IO client. ```csharp using var client = new SocketIO(new Uri("http://localhost:3000")); await client.ConnectAsync(); // ... use client ... // Dispose called automatically ``` -------------------------------- ### Graceful Shutdown with try-finally Source: https://github.com/doghappy/socket.io-client-csharp/blob/master/_autodocs/GUIDE.md Demonstrates a graceful shutdown pattern for the Socket.IO client using a try-finally block to ensure disconnection and disposal. ```csharp try { await client.ConnectAsync(); // ... use client ... } finally { if (client.Connected) { await client.DisconnectAsync(); } client.Dispose(); } ``` -------------------------------- ### Configure System.Text.Json Serializer Source: https://github.com/doghappy/socket.io-client-csharp/blob/master/README.md Use this snippet to configure System.Text.Json with custom JsonSerializerOptions when initializing the SocketIO client. ```csharp var client = new SocketIO(new Uri("http://localhost:11400"), services => { services.AddSystemTextJson(new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase }); }); ``` -------------------------------- ### SocketIOOptions Constructor Source: https://github.com/doghappy/socket.io-client-csharp/blob/master/_autodocs/api-reference/SocketIOOptions.md Creates a new instance of SocketIOOptions with default values for all configurable properties. ```APIDOC ## SocketIOOptions() ### Description Creates a new instance of `SocketIOOptions` with default values. ### Default Values - `EIO`: `EngineIO.V4` - `ConnectionTimeout`: 30 seconds - `Reconnection`: `true` - `ReconnectionAttempts`: 10 - `ReconnectionDelayMax`: 5000 milliseconds - `Transport`: `TransportProtocol.Polling` - `AutoUpgrade`: `true` - `Path`: `/socket.io/` ### Example ```csharp var options = new SocketIOOptions(); var client = new SocketIO(new Uri("http://localhost:3000"), options); ``` ``` -------------------------------- ### Respond with Acknowledgment Source: https://github.com/doghappy/socket.io-client-csharp/blob/master/_autodocs/GUIDE.md Handle incoming events and send back data as an acknowledgment using `ctx.SendAckDataAsync`. ```csharp client.On("calculate", async ctx => { var a = ctx.GetValue(0); var b = ctx.GetValue(1); var result = a + b; await ctx.SendAckDataAsync(new object[] { result }); }); ``` -------------------------------- ### Bidirectional Acknowledgments Source: https://github.com/doghappy/socket.io-client-csharp/blob/master/_autodocs/GUIDE.md Demonstrates handling incoming requests with acknowledgments and sending requests that expect acknowledgments. ```csharp client.On("calculate", async ctx => { var a = ctx.GetValue(0); var b = ctx.GetValue(1); var result = a + b; await ctx.SendAckDataAsync(new object[] { result }); }); // Client sends request and gets response await client.EmitAsync("calculate", new[] { 10, 20 }, ack => { var result = ack.GetValue(0); Console.WriteLine($"10 + 20 = {result}"); return Task.CompletedTask; }); ``` -------------------------------- ### Add Query Parameters for Handshake Source: https://github.com/doghappy/socket.io-client-csharp/blob/master/_autodocs/api-reference/SocketIOOptions.md Configures query string parameters to be sent during the initial connection handshake. Useful for authentication or metadata. ```csharp var options = new SocketIOOptions { Query = new NameValueCollection { ["token"] = "abc123", ["userId"] = "42" } }; ``` -------------------------------- ### Configure Socket.IO Client with Custom Path Source: https://github.com/doghappy/socket.io-client-csharp/blob/master/_autodocs/configuration.md Use this when your Socket.IO server is hosted at a non-standard path. The path setter automatically normalizes the provided path. ```csharp var client = new SocketIO( new Uri("http://localhost:3000"), new SocketIOOptions { Path = "/custom/socket.io" } ); // Note: Path setter automatically normalizes to `/custom/socket.io/` ``` -------------------------------- ### Connect to Server Asynchronously Source: https://github.com/doghappy/socket.io-client-csharp/blob/master/_autodocs/api-reference/SocketIO.md Asynchronously connects to the Socket.IO server. Use this method when no cancellation is required. Handles connection exceptions and timeouts. ```csharp try { await client.ConnectAsync(); Console.WriteLine("Connected to server"); } catch (ConnectionException ex) { Console.WriteLine($"Connection failed: {ex.Message}"); } ``` -------------------------------- ### SocketIOOptions Query Source: https://github.com/doghappy/socket.io-client-csharp/blob/master/_autodocs/api-reference/SocketIOOptions.md Allows setting custom query string parameters to be sent with the initial connection handshake request. ```APIDOC ## SocketIOOptions Query ### Description Gets or sets query string parameters to send during the connection handshake. These parameters are appended to the connection URL. ### Method `NameValueCollection? Query { get; set; }` ### Parameters #### Property - **Query** (`NameValueCollection?`) - Required - Query parameters for the initial handshake request. ### Remarks - Parameters are sent as query strings in the initial connection request. - Useful for authentication tokens, device identifiers, or other metadata. - Multiple values for the same key are supported. - Applied only during initial connection, not on subsequent operations. - Use `IServerResponse` metadata in more advanced scenarios. ### Example ```csharp var options = new SocketIOOptions { Query = new NameValueCollection { ["token"] = "abc123", ["userId"] = "42" } }; ``` ``` -------------------------------- ### ISocketIO Interface Reference Source: https://github.com/doghappy/socket.io-client-csharp/blob/master/_autodocs/MANIFEST.txt Documentation for the public interface `ISocketIO`, outlining the contract for Socket.IO client implementations. This includes methods and properties that clients must expose. ```APIDOC ## ISocketIO Interface Reference This section details the public interface `ISocketIO`, which defines the contract for Socket.IO client implementations. It specifies the methods and properties that users can interact with. ### Methods All methods defined in the `ISocketIO` interface are documented, including their signatures and purpose. ### Properties Public properties exposed by the `ISocketIO` interface are documented. ``` -------------------------------- ### Configure System.Text.Json Serializer Source: https://github.com/doghappy/socket.io-client-csharp/blob/master/_autodocs/api-reference/Serializers.md Configures JsonSerializerOptions for System.Text.Json and registers the SystemJsonSerializer with the SocketIO client. This is the default serializer and requires no additional NuGet package. ```csharp var options = new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase, PropertyNameCaseInsensitive = true, WriteIndented = false }; var client = new SocketIO(new Uri("http://localhost:3000"), services => { services.AddSystemTextJson(options); }); ``` -------------------------------- ### On(string, Func) Source: https://github.com/doghappy/socket.io-client-csharp/blob/master/_autodocs/api-reference/SocketIO.md Registers a listener for a specific event. The handler is invoked every time the event is received. If a handler is already registered for this event, it is replaced. ```APIDOC ## On(string, Func) ### Description Registers a listener for a specific event. The handler is invoked every time the event is received. If a handler is already registered for this event, it is replaced. ### Method Signature `public void On(string eventName, Func handler)` ### Parameters #### Path Parameters - **eventName** (string) - Yes - The name of the event to listen for (case-sensitive) - **handler** (Func) - Yes - Async callback that handles the event ### Remarks - The handler is called on an internal event loop and should avoid blocking operations. - Event handlers run sequentially for a given event. - Unhandled exceptions in handlers are logged but do not terminate the client. ### Example ```csharp client.On("message", ctx => { var text = ctx.GetValue(0); Console.WriteLine($"Received: {text}"); return Task.CompletedTask; }); ``` ```