SuperSocket Documentation

repository·master·Indexed 26 days ago

https://github.com/kerryjiang/supersocket

A high-performance, extensible socket server application framework for .NET designed for building custom network communication applications. It supports multiple protocols including TCP, UDP, WebSocket, and HTTP, and provides specialized components such as SuperSocket.Server, SuperSocket.Client, and SuperSocket.ProtoBase. The framework includes support for MCP (Model Context Protocol) via HTTP and Stdio transports, as well as HTTP Keep-Alive server implementations.

Tokens
16.3K
Snippets
44
Records
89
Agent score
87%

What's inside SuperSocket

  1. Overview of SuperSocket

    master

    SuperSocket is a high-performance, extensible socket server application framework for .NET. It provides a robust architecture for building custom network communication applications, supporting multiple protocols including TCP, UDP, and WebSocket.

    Key features include:

    • Flexible Pipeline Architecture: Uses a pipeline processing model with customizable filters for efficient data handling.
    • Protocol Abstraction: Simplifies implementation of various protocols (TCP, UDP, WebSocket, or custom).
    • Middleware Support: Extensible system for custom connection and packet processing.
    • Session Management: Comprehensive lifecycle management for connections.
    • Command Processing: Efficient request handling based on a command model.
    • Modern .NET Integration: Seamlessly integrates with .NET Dependency Injection, Configuration, and Logging.
    • High Performance: Designed for high throughput and low latency using buffer pools and minimal memory allocation.
    • Cross-Platform: Runs on all platforms supported by .NET.
  2. Use constructor injection in Pipeline Filters

    master

    Starting with version 2.0.2-beta.1, SuperSocket pipeline filters no longer require a parameterless constructor. You can now use constructor injection to provide dependencies (such as ILogger or IConfiguration) to your pipeline filters. This change is backward compatible; filters with default constructors will continue to function normally.

    public class MyPipelineFilter : IPipelineFilter<TextPackageInfo>
    {
        private readonly ILogger<MyPipelineFilter> _logger;
        private readonly IConfiguration _configuration;
    
        // Constructor with dependencies - now supported!
        public MyPipelineFilter(ILogger<MyPipelineFilter> logger, IConfiguration configuration)
        {
            _logger = logger;
            _configuration = configuration;
        }
    
        // Implementation details...
    }
    
    // Register and use the filter
    hostBuilder.AsSuperSocketHostBuilder<TextPackageInfo, MyPipelineFilter>();
  3. Logging best practices for MCP Stdio servers

    master

    When developing MCP servers using stdio, you must avoid writing logs to stdout as it is reserved for the MCP protocol communication.

    • Protocol Communication: Must happen on stdout.
    • Logging: Send logs (warning level and above) to stderr to avoid interfering with the client.
    • Debug Info: Should be directed to files if necessary.
  4. Integrate the MCP Stdio Server with MCP clients

    master

    To use this server as an MCP server in a client (like Claude Desktop or other MCP-compatible clients), configure the client to spawn the server as a subprocess using the following JSON configuration structure:

    {
      "mcpServers": {
        "supersocket-mcp": {
          "command": "dotnet",
          "args": ["run", "--project", "/path/to/McpStdioServer"],
          "cwd": "/path/to/McpStdioServer"
        }
      }
    }
  5. Register MCP Handlers using McpHandlerRegistry

    master

    To provide functionality to your MCP server, you must register handlers for tools, resources, and prompts. Use the McpHandlerRegistry to create a single registration point that can be shared between TCP (McpServer) and HTTP (McpHttpServer) implementations.

    // Create handler registry
    var handlerRegistry = new McpHandlerRegistry(logger);
    
    // Register handlers once - usable by both TCP and HTTP
    handlerRegistry.RegisterTool("echo", new EchoToolHandler());
    handlerRegistry.RegisterResource("file://example", new FileResourceHandler());
    handlerRegistry.RegisterPrompt("greeting", new GreetingPromptHandler());
  6. Create an HTTP MCP Server

    master

    To set up an MCP server over HTTP, use the SuperSocketHostBuilder with McpHttpRequest and McpHttpPipelineFilter. Use .UseMcpCommands(serverInfo) to register the standard MCP command set. The command registration logic is identical to the TCP implementation, allowing for code reuse across different transports.

    using SuperSocket.MCP.Extensions;
    using SuperSocket.MCP.Models;
    using SuperSocket.Server.Host;
    
    var serverInfo = new McpServerInfo
    {
        Name = "MyMcpHttpServer",
        Version = "1.0.0"
    };
    
    var host = SuperSocketHostBuilder.Create<McpHttpRequest, McpHttpPipelineFilter>()
        .UseMcpCommands(serverInfo)  // Same command registration
        .ConfigureAppConfiguration((hostCtx, configApp) =>
        {
            configApp.AddInMemoryCollection(new Dictionary<string, string>
            {
                { "serverOptions:name", "McpHttpServer" },
                { "serverOptions:listeners:0:ip", "Any" },
                { "serverOptions:listeners:0:port", "8080" }
            });
        })
        .Build();
    
    await host.RunAsync();
  7. Install SuperSocket NuGet packages

    master

    SuperSocket is distributed via NuGet packages. Depending on your requirements, you can install specific modules for server functionality, client support, or specific protocols.

    Commonly used packages include:

    • SuperSocket.Server: Core server functionality.
    • SuperSocket.Client: Client components for connecting to servers.
    • SuperSocket.WebSocket: WebSocket protocol support.
    • SuperSocket.Udp: UDP protocol support.
    • SuperSocket.Command: Command-based processing.
    • SuperSocket.ProtoBuf: Protobuf support.
    • SuperSocket.MessagePack: MessagePack support.
  8. Implement a Server-Sent Events (SSE) Stream

    master

    To implement real-time data streaming via SSE, check if a request is an SSE request using request.IsSSERequest(). You can then start an SSE stream using session.StartSSEAsync(), which returns a ServerSentEventWriter. Use this writer to send events, JSON payloads, or start an automatic heartbeat to keep the connection alive.

    .UsePackageHandler(async (session, request) =>
    {
        if (request.Path == "/events" && request.IsSSERequest())
        {
            // Start SSE stream
            var sseWriter = await session.StartSSEAsync();
            
            // Send events
            await sseWriter.SendEventAsync("Hello SSE!", "greeting");
            await sseWriter.SendJsonEventAsync("{\"type\": \"data\", \"value\": 42}");
            
            // Start automatic heartbeat
            _ = sseWriter.StartHeartbeatAsync(cancellationToken);
            
            // Send more events as needed...
            await sseWriter.SendCloseEventAsync();
        }
        else
        {
            await session.SendHttpResponseAsync(200, "Use /events for SSE", "text/plain");
        }
    })
  9. Use HTTP Keep-Alive and Server-Sent Events (SSE)

    master

    SuperSocket supports persistent HTTP connections and real-time event streaming via SSE.

    HTTP Keep-Alive Enable persistent connections by setting the KeepAlive property to true in your HTTP request/response handling. This allows for HTTP/1.1 compliant connection reuse and improved performance.

    Server-Sent Events (SSE) For real-time event streaming (text/event-stream), use SseSessionExtensions to manage event streaming, heartbeats, and reconnections.

  10. Upgrade to SuperSocket 2.0.1

    master
    SuperSocket 2.0.1 is a maintenance release that is fully compatible with SuperSocket 2.0.0. It is recommended to upgrade to this version to benefit from stability fixes (specifically in middleware session handling and SocketSender), performance improvements in SendAsync, and enhanced dependency injection support for pipeline filters.