SuperSocket 2.0 Server Startup via Configuration

1. Create the project

Create a .NET Core console application in Visual Studio 2019, selecting .NET Core 3.1 as the target framework. Add the SuperSocket (2.0.0-beta.8) package via NuGet.

2. Add configuration file

Place a appsettings.json file in the project root and set its Copy to Output Directory property to Copy if newer.

// Configuration options // name: Server name. // maxPackageLength: Maximum allowed packet size (default 4 MB). // receiveBufferSize: Receive buffer size (default 4 KB). // sendBufferSize: Send buffer size (default 4 KB). // receiveTimeout: Receive timeout in microseconds. // sendTimeout: Send timeout in microseconds. // listeners: Server listeners. // listeners//ip: Listening IP (Any for all IPv4, IPv6Any for all IPv6, or a specific IP address). // listeners//port: Listening port. // listeners//backLog: Maximum length of the pending connection queue. // listeners//noDelay: Enable or disable Nagle's algorithm. // listeners//security: TLS protocol version (None/Ssl3/Tls11/Tls12/Tls13). // listeners//certificateOptions: Certificate settings for TLS encryption/decryption.


</div>**3. Application code (rewirtten for structure and variable clarity)**

<div>```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using SuperSocket;
using SuperSocket.ProtoBase;

namespace SocketServer.ConfigDemo
{
    class Program
    {
        private static readonly Dictionary<string, Func<IList<string>, string>> ArithmeticCommands =
            new Dictionary<string, Func<IList<string>, string>>(StringComparer.OrdinalIgnoreCase)
            {
                ["ADD"]  = args => args.Select(int.Parse).Sum().ToString(),
                ["SUB"]  = args => args.Select(int.Parse).Aggregate((a, b) => a - b).ToString(),
                ["MULT"] = args => args.Select(int.Parse).Aggregate((a, b) => a * b).ToString()
            };

        static async Task Main(string[] args)
        {
            var serverHost = SuperSocketHostBuilder.Create<StringPackageInfo, CommandLinePipelineFilter>()
                .UseSessionHandler(
                    async (clientSession) =>
                    {
                        Console.WriteLine($"[Connected] {clientSession.RemoteEndPoint}");
                        var welcomeMsg = $"Welcome! Your address: {clientSession.RemoteEndPoint}\r\n";
                        await clientSession.SendAsync(Encoding.UTF8.GetBytes(welcomeMsg));
                    },
                    async (clientSession, closeReason) =>
                    {
                        Console.WriteLine($"[Closed] {clientSession.RemoteEndPoint} - Reason: {closeReason}");
                    })
                .UsePackageHandler(async (clientSession, receivedPackage) =>
                {
                    Console.WriteLine($"Package from {clientSession.RemoteEndPoint}: command={receivedPackage.Key}");
                    var upperCommand = receivedPackage.Key?.ToUpperInvariant() ?? "";
                    string response;

                    if (upperCommand == "ECHO")
                    {
                        response = receivedPackage.Body ?? "";
                    }
                    else if (ArithmeticCommands.TryGetValue(upperCommand, out var handler))
                    {
                        try
                        {
                            response = handler(receivedPackage.Parameters ?? new List<string>());
                        }
                        catch (Exception ex)
                        {
                            response = $"Error: {ex.Message}";
                        }
                    }
                    else
                    {
                        response = "Unknown command";
                    }

                    await clientSession.SendAsync(Encoding.UTF8.GetBytes(response + "\r\n"));
                })
                .ConfigureLogging((hostContext, loggingBuilder) =>
                {
                    loggingBuilder.AddConsole();
                })
                .Build();

            await serverHost.RunAsync();
        }
    }
}

Tags: SuperSocket .NET Core appsettings.json Socket Server StringPackageInfo

Posted on Fri, 04 Sep 2026 16:11:16 +0000 by Jakehh