You are an expert C# developer, specializing in high performance and multi-threaded applications development. Write a C# implementation for .NET framework 4.8 of a TLS server that listens on loopback interface and which accepts multiple simultaneous clients in parallel, each client sending multiple commands (byte array) and receiving associated responses (byte array) from the server. The server run in the background on the command line application. The commands received from clients are processed through a dedicated class implementing the processing of each supported commands. The user can stop the server at any moment by entering "QUIT". The self-certificate used by this TLS server is generated when the program start and its fingerprint is printed on the console.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Here's a C# implementation of a TLS server that meets your requirements. This example uses the System.Net.Security.SslStream class for TLS communication and the System.Threading.Tasks.Dataflow library for processing commands in parallel. Make sure to install the System.Threading.Tasks.Dataflow NuGet package.
csharp
using System;
using System.Collections.Concurrent;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Net.Sockets;
using System.Security.Authentication;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Threading.Tasks.Dataflow;
namespace TlsServer
{
public class CommandProcessor
{
public byte[] ProcessCommand(byte[] command)
{
// Implement your command processing logic here
return Encoding.UTF8.GetBytes($"Processed command: {Encoding.UTF8.GetString(command)}");
}
}
public class TlsServer
{
private const int Port = 8080;
private const string CertificateName = "localhost";
private readonly X509Certificate2 _certificate;
private readonly TcpListener _listener;
private readonly CommandProcessor _commandProcessor;
private readonly ActionBlock<TcpClient> _clientHandler;
private readonly CancellationTokenSource _cancellationTokenSource;
public TlsServer()
{
_certificate = GenerateSelfSignedCertificate();
_listener = new TcpListener(IPAddress.Loopback, Port);
_commandProcessor = new CommandProcessor();
_cancellationTokenSource = new CancellationTokenSource();
_clientHandler = new ActionBlock<TcpClient>(HandleClient, new ExecutionDataflowBlockOptions
{
MaxDegreeOfParallelism = DataflowBlockOptions.Unbounded,
CancellationToken = _cancellationTokenSource.Token
});
}
public void Start()
{
_listener.Start();
Console.WriteLine($"TLS server started on {_listener.LocalEndpoint}. Press 'QUIT' to stop the server.");
Task.Run(() =>
{
while (!_cancellationTokenSource.IsCancellationRequested)
{
if (_listener.Pending())
{
_clientHandler.Post(_listener.AcceptTcpClient());
}
else
{
Thread.Sleep(100);
}
}
});
while (true)
{
var input = Console.ReadLine();
if (input?.ToUpper() == "QUIT")
{
_cancellationTokenSource.Cancel();
break;
}
}
_listener.Stop();
_clientHandler.Complete();
_clientHandler.Completion.Wait();
}
private void HandleClient(TcpClient client)
{
using (client)
{
using var stream = new SslStream(client.GetStream(), false, ValidateServerCertificate);
stream.AuthenticateAsServer(_certificate, false, SslProtocols.Tls12, true);
Console.WriteLine($"Client connected: {client.Client.RemoteEndPoint}");
while (client.Connected && !_cancellationTokenSource.IsCancellationRequested)
{
try
{
var command = ReadCommand(stream);
if (command == null)
{
break;
}
var response = _commandProcessor.ProcessCommand(command);
WriteResponse(stream, response);
}
catch (Exception e)
{
Console.WriteLine($"Error processing command: {e.Message}");
break;
}
}
Console.WriteLine($"Client disconnected: {client.Client.RemoteEndPoint}");
}
}
private byte[] ReadCommand(SslStream stream)
{
var buffer = new byte[1024];
var totalRead = 0;
var commandLength = 0;
while (totalRead < 4)
{
var read = stream.Read(buffer, totalRead, 4 - totalRead);
if (read == 0)
{
return null;
}
totalRead += read;
}
commandLength = BitConverter.ToInt32(buffer, 0);
var command = new byte[commandLength];
totalRead = 0;
while (totalRead < commandLength)
{
var read = stream.Read(command, totalRead, commandLength - totalRead);
if (read == 0)
{
return null;
}
totalRead += read;
}
return command;
}
private void WriteResponse(SslStream stream, byte[] response)
{
var responseLength = response.Length;
var lengthBytes = BitConverter.GetBytes(responseLength);
stream.Write(lengthBytes, 0, 4);
stream.Write(response, 0, responseLength);
}
private bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
if (sslPolicyErrors == SslPolicyErrors.None)
{
return true;
}
Console.WriteLine($"Certificate error: {sslPolicyErrors}");
return false;
}
private X509Certificate2 GenerateSelfSignedCertificate()
{
using var rsa = RSA.Create(2048);
var request = new CertificateRequest(
$"CN={CertificateName}",
rsa,
HashAlgorithmName.SHA256,
RSASignaturePadding.Pkcs1);
request.CertificateExtensions.Add(
new X509BasicConstraintsExtension(true, false, 0, true));
request.CertificateExtensions.Add(
new X509SubjectKeyIdentifierExtension(request.PublicKey, false));
var certificate = request.CreateSelfSigned(
DateTimeOffset.Now.AddDays(-1),
DateTimeOffset.Now.AddYears(1));
Console.WriteLine($"Certificate fingerprint: {certificate.Thumbprint}");
return certificate;
}
}
class Program
{
static void Main(string[] args)
{
var server = new TlsServer();
server.Start();
}
}
}
This implementation generates a self-signed certificate when the program starts, listens on the loopback interface, accepts multiple simultaneous clients in parallel, and processes commands through a dedicated class. The user can stop the server by entering "QUIT".