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.
To create a TLS server that meets your requirements, we'll use the SslStream class to handle the TLS connection. We will also utilize the TcpListener class to accept connections and the Task class to process multiple clients concurrently.
First, let's create a new Console App (.NET Framework) project in Visual Studio targeting .NET Framework 4.8. Then, add the following code to the Program.cs file:
csharp
using System;
using System.IO;
using System.Net;
using System.Net.Security;
using System.Net.Sockets;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
namespace TLSServer
{
public class CommandProcessor
{
// Implement your command processing logic here.
public byte[] ProcessCommand(byte[] command)
{
// Placeholder implementation: Echo back the command.
return command;
}
}
public static class Server
{
private const int Port = 12345;
private static readonly IPAddress LoopbackAddress = IPAddress.Loopback;
private static TcpListener _listener;
private static bool _isRunning = true;
public static async Task Start()
{
_listener = new TcpListener(LoopbackAddress, Port);
_listener.Start();
Console.WriteLine("TLS server started. Listening on port " + Port);
while (_isRunning)
{
var clientSocket = await _listener.AcceptTcpClientAsync();
var task = Task.Run(() => HandleClient(clientSocket));
}
}
public static void Stop()
{
_isRunning = false;
_listener.Stop();
Console.WriteLine("TLS server stopped.");
}
private static async Task HandleClient(TcpClient client)
{
try
{
using var sslStream = new SslStream(client.GetStream(), false, new RemoteCertificateValidationCallback(ValidateServerCertificate), null);
await sslStream.AuthenticateAsServerAsync(GetSelfSignedCertificate());
while (_isRunning)
{
var command = new byte[1024];
var bytesRead = await sslStream.ReadAsync(command, 0, command.Length);
if (bytesRead == 0)
{
break;
}
var response = ProcessCommand(command, bytesRead);
await sslStream.WriteAsync(response, 0, response.Length);
}
}
catch (Exception ex)
{
Console.WriteLine("Error handling client: " + ex.Message);
}
finally
{
client.Close();
}
}
private static X509Certificate2 GetSelfSignedCertificate()
{
var rsa = RSA.Create(2048);
var certRequest = new CertificateRequest("CN=localhost", rsa, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
certRequest.CertificateExtensions.Add(new X509BasicConstraintsExtension(true, false, 0, true));
var certificate = certRequest.CreateSelfSigned(DateTimeOffset.UtcNow, DateTimeOffset.UtcNow.AddYears(1));
var certBytes = certificate.Export(X509ContentType.Pfx);
var certFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "self-signed.pfx");
File.WriteAllBytes(certFile, certBytes);
return new X509Certificate2(certFile, string.Empty);
}
private static byte[] ProcessCommand(byte[] command, int bytesRead)
{
var processor = new CommandProcessor();
return processor.ProcessCommand(command.Take(bytesRead).ToArray());
}
private static bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
return true;
}
}
class Program
{
static void Main(string[] args)
{
var fingerprint = GetCertificateFingerprint(Server.GetSelfSignedCertificate());
Console.WriteLine("Self-signed certificate fingerprint: " + fingerprint);
Task.Run(async () =>
{
await Server.Start();
});
Console.WriteLine("Type 'QUIT' to stop the server.");
while (true)
{
var input = Console.ReadLine();
if (input.ToUpper() == "QUIT")
{
Server.Stop();
break;
}
}
}
private static string GetCertificateFingerprint(X509Certificate2 certificate)
{
var sha1 = SHA1.Create();
var hash = sha1.ComputeHash(certificate.GetRawCertData());
var sb = new StringBuilder();
foreach (var b in hash)
{
sb.Append(b.ToString("x2"));
}
return sb.ToString();
}
}
}
This code creates a TLS server that listens on the loopback interface (127.0.0.1) on port 12345. It generates a self-signed certificate when the program starts and prints its fingerprint to the console. The server accepts multiple simultaneous clients in parallel and processes their commands using the CommandProcessor class. The user can stop the server by entering "QUIT" in the console.
Please note that the CommandProcessor class is not implemented in this example. You should replace the placeholder implementation with your own command processing logic.
“You are an expert C# developer, specializing in high performance and multi-threaded….” Conversation with qwen2-72b-instruct, from the LMArena Human Preference 100K dataset. The Chat Archive, 2026. https://thechatarchive.com/c/01m851cnfg5y6r0dgfkdbhaf09