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 listens on the loopback interface, accepts multiple simultaneous clients, and processes commands using a dedicated class. The server runs in the background and can be stopped by entering "QUIT". The self-signed certificate is generated when the program starts, and its fingerprint is printed on the console.
csharp
using System;
using System.IO;
using System.IO.Pipelines;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Net.Sockets;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
public class TlsServer
{
private readonly TcpListener _listener;
private readonly SslServerAuthenticationOptions _sslOptions;
private readonly CommandProcessor _commandProcessor;
private CancellationTokenSource _cancellationTokenSource;
public TlsServer(int port, CommandProcessor commandProcessor)
{
_listener = new TcpListener(IPAddress.Loopback, port);
_listener.Start();
_sslOptions = new SslServerAuthenticationOptions
{
ClientCertificateRequired = false,
Certificates = new X509CertificateCollection
{
GenerateSelfSignedCertificate(new X509Name("CN=SelfSignedServer"))
}
};
_commandProcessor = commandProcessor;
_cancellationTokenSource = new CancellationTokenSource();
}
public async Task StartAsync()
{
Console.WriteLine($"TLS Server listening on port {_listener.Port}");
Console.WriteLine($"Self-signed certificate fingerprint: {GetCertificateFingerprint(_sslOptions.Certificates.First())}");
while (!_cancellationTokenSource.IsCancellationRequested)
{
TcpClient client = await _listener.AcceptTcpClientAsync(_cancellationTokenSource.Token);
Task.Run(() => HandleClient(client));
}
}
public void Stop()
{
_cancellationTokenSource.Cancel();
_listener.Stop();
}
private async Task HandleClient(TcpClient client)
{
using (var stream = client.GetStream())
using (var sslStream = new SslStream(stream, false, new RemoteCertificateValidationCallback(ValidateClientCertificate), null))
{
await sslStream.AuthenticateAsServerAsync(_sslOptions, _cancellationTokenSource.Token);
while (true)
{
byte[] buffer = new byte[4096];
int bytesRead = await sslStream.ReadAsync(buffer, 0, buffer.Length, _cancellationTokenSource.Token);
if (bytesRead == 0)
{
break;
}
byte[] command = buffer.Take(bytesRead).ToArray();
byte[] response = _commandProcessor.ProcessCommand(command);
await sslStream.WriteAsync(response, 0, response.Length, _cancellationTokenSource.Token);
}
}
client.Close();
}
private bool ValidateClientCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
// For simplicity, we always accept client certificates here
return true;
}
private static string GetCertificateFingerprint(X509Certificate certificate)
{
using (var sha1 = SHA1.Create())
{
byte[] hash = sha1.ComputeHash(certificate.RawData);
return BitConverter.ToString(hash).Replace("-", "").ToLower();
}
}
}
public interface ICommandProcessor
{
byte[] ProcessCommand(byte[] command);
}
// Example implementation of ICommandProcessor
public class ExampleCommandProcessor : ICommandProcessor
{
public byte[] ProcessCommand(byte[] command)
{
// Process the command and return the response
return Encoding.UTF8.GetBytes($"Response to command: {Encoding.UTF8.GetString(command)}");
}
}
class Program
{
static async Task Main(string[] args)
{
var commandProcessor = new ExampleCommandProcessor();
var server = new TlsServer(443, commandProcessor);
Task.Run(async () =>
{
while (true)
{
string input = Console.ReadLine();
if (input.ToLower() == "quit")
{
server.Stop();
break;
}
}
});
await server.StartAsync();
}
}
This implementation creates a TLS server that listens on port 443 (you can change it as needed). It uses a self-signed certificate generated at startup and prints its fingerprint to the console. The CommandProcessor interface is used to process commands received from clients, and an example implementation (ExampleCommandProcessor) is provided.
The server accepts multiple simultaneous clients and processes their commands in parallel. It can be stopped by entering "QUIT" in the console.