Back to Documentation

C# SDK Examples

Real-world examples showing how to use the OddSockets C# SDK in production .NET applications

Try Console Example
Basic Usage
Available
Simple example showing how to connect, subscribe to a channel, and publish messages using the core SDK functionality.
using OddSockets;
using OddSockets.Models;

var config = new OddSocketsConfig
{
    ApiKey = "ak_live_1234567890abcdef"
};

var client = new OddSocketsClient(config);

// Connect to OddSockets
await client.ConnectAsync();

var channel = client.Channel("my-channel");

// Subscribe to messages
await channel.SubscribeAsync(message =>
{
    Console.WriteLine($"Received: {message.Data}");
});

// Publish a message
await channel.PublishAsync("Hello, World!");
ASP.NET Core Web API
Available
Complete ASP.NET Core Web API integration showing dependency injection, controllers, and real-time messaging endpoints.
// Program.cs
builder.Services.AddSingleton(new OddSocketsConfig
{
    ApiKey = builder.Configuration["OddSockets:ApiKey"]!,
    AutoConnect = true
});

builder.Services.AddSingleton<OddSocketsClient>();

// Controllers/ChatController.cs
[ApiController]
[Route("api/[controller]")]
public class ChatController : ControllerBase
{
    private readonly OddSocketsClient _client;

    public ChatController(OddSocketsClient client)
    {
        _client = client;
    }

    [HttpPost("channels/{channelName}/messages")]
    public async Task<IActionResult> SendMessage(
        string channelName, 
        [FromBody] object message)
    {
        var channel = _client.Channel(channelName);
        var result = await channel.PublishAsync(message);
        return Ok(result);
    }
}
Blazor Server
Available
Real-time Blazor Server application with live chat functionality, showing component integration and state management.
@page "/chat"
@using OddSockets
@using OddSockets.Models
@inject OddSocketsClient Client
@implements IDisposable

<h3>Real-time Chat</h3>

<div class="chat-messages">
    @foreach (var message in messages)
    {
        <div class="message">
            <strong>@message.UserId:</strong> @message.Data
        </div>
    }
</div>

@code {
    private List<Message> messages = new();
    private OddSocketsChannel? channel;

    protected override async Task OnInitializedAsync()
    {
        channel = Client.Channel("blazor-chat");
        
        await channel.SubscribeAsync(message =>
        {
            messages.Add(message);
            InvokeAsync(StateHasChanged);
        });
    }
}
Worker Service
Available
Background service implementation for processing real-time notifications and messages in server applications.
public class ChatWorkerService : BackgroundService
{
    private readonly OddSocketsClient _client;
    private readonly ILogger<ChatWorkerService> _logger;

    public ChatWorkerService(
        OddSocketsClient client, 
        ILogger<ChatWorkerService> logger)
    {
        _client = client;
        _logger = logger;
    }

    protected override async Task ExecuteAsync(
        CancellationToken stoppingToken)
    {
        await _client.ConnectAsync(stoppingToken);
        
        var channel = _client.Channel("worker-notifications");
        
        await channel.SubscribeAsync(async message =>
        {
            _logger.LogInformation(
                "Received notification: {Message}", 
                message.Data);
            
            await ProcessNotification(message);
        }, cancellationToken: stoppingToken);

        await Task.Delay(Timeout.Infinite, stoppingToken);
    }
}
Console Application
Available
Interactive console application demonstrating real-time messaging with user input and message display.
using OddSockets;
using OddSockets.Models;

var config = new OddSocketsConfig
{
    ApiKey = "ak_live_1234567890abcdef",
    UserId = "console-user"
};

var client = new OddSocketsClient(config);

try
{
    await client.ConnectAsync();
    Console.WriteLine("Connected to OddSockets!");

    var channel = client.Channel("console-chat");

    await channel.SubscribeAsync(message =>
    {
        Console.WriteLine(
            $"[{message.Timestamp:HH:mm:ss}] " +
            $"{message.UserId}: {message.Data}");
    });

    Console.WriteLine("Type messages (or 'quit' to exit):");

    string? input;
    while ((input = Console.ReadLine()) != "quit")
    {
        if (!string.IsNullOrWhiteSpace(input))
        {
            await channel.PublishAsync(input);
        }
    }
}
finally
{
    await client.DisconnectAsync();
}
MAUI Cross-Platform
Available
.NET Multi-platform App UI (MAUI) example showing real-time messaging in mobile and desktop applications.
// MauiProgram.cs
public static class MauiProgram
{
    public static MauiApp CreateMauiApp()
    {
        var builder = MauiApp.CreateBuilder();
        builder.UseMauiApp<App>();

        builder.Services.AddSingleton(new OddSocketsConfig
        {
            ApiKey = "ak_live_1234567890abcdef",
            AutoConnect = true
        });

        builder.Services.AddSingleton<OddSocketsClient>();
        builder.Services.AddSingleton<MainPage>();

        return builder.Build();
    }
}

// MainPage.xaml.cs
public partial class MainPage : ContentPage
{
    private readonly OddSocketsClient _client;
    private OddSocketsChannel? _channel;

    protected override async void OnAppearing()
    {
        _channel = _client.Channel("maui-chat");
        
        await _channel.SubscribeAsync(message =>
        {
            MainThread.BeginInvokeOnMainThread(() =>
            {
                DisplayMessage(message);
            });
        });
    }
}