// Collection of code snippets by Arne Vajhøj // (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) using System; using System.Security.Cryptography.X509Certificates; using System.IO; using System.Net; using System.Net.Security; using System.Net.Sockets; using System.Security.Authentication; namespace SocketDemo.Text.SecureHigh.SingleServer { public class Program { private const int PORT = 12345; private const int BACKLOG = 100; public static void Main(string[] args) { // listen on port TcpListener srv = new TcpListener(IPAddress.Any, PORT); srv.Start(BACKLOG); while(true) { // accept connection TcpClient cli = srv.AcceptTcpClient(); // get reader and writer NetworkStream stm = cli.GetStream(); SslStream sslstm = new SslStream(stm); X509Certificate cert = new X509Certificate2(@"\work\sslserver.pfx", "topsecret"); sslstm.AuthenticateAsServer(cert, false, SslProtocols.Tls12, true); StreamReader sr = new StreamReader(sslstm); StreamWriter sw = new StreamWriter(sslstm); Console.WriteLine("(connection from {0})", cli.Client.RemoteEndPoint); // read a and b string line = sr.ReadLine(); string[] parts = line.Split(' '); int a = int.Parse(parts[0]); int b = int.Parse(parts[1]); // calculate c and send int c = a + b; sw.WriteLine(c); sw.Flush(); // read v string v = sr.ReadLine(); // calculate v2 and send string v2 = v + v; sw.WriteLine(v2); sw.Flush(); // close connection sr.Close(); sw.Close(); cli.Close(); } } } }