// 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; using System.Text; using System.Threading; namespace SocketDemo.Binary.SecureHigh.MultiServer { public class Program { private static int HTON(int v) { if(BitConverter.IsLittleEndian) { byte[] buf = BitConverter.GetBytes(v); Array.Reverse(buf); return BitConverter.ToInt32(buf, 0); } else { return v; } } private static int NTOH(int v) { if(BitConverter.IsLittleEndian) { byte[] buf = BitConverter.GetBytes(v); Array.Reverse(buf); return BitConverter.ToInt32(buf, 0); } else { return v; } } private class ClientHandler { private TcpClient cli; public ClientHandler(TcpClient cli) { this.cli = cli; } public void Run() { Console.WriteLine("(handler in thread {0})", Thread.CurrentThread.ManagedThreadId); // 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); BinaryReader br = new BinaryReader(sslstm); BinaryWriter bw = new BinaryWriter(sslstm); // read a and b int a = NTOH(br.ReadInt32()); int b = NTOH(br.ReadInt32()); // calculate c and send int c = a + b; bw.Write(HTON(c)); bw.Flush(); // read v int buflen = br.ReadByte(); byte[] buf = new byte[buflen]; int ix = 0; while(ix < buf.Length) { ix += br.Read(buf, ix, buf.Length - ix); } string v = Encoding.UTF8.GetString(buf); // calculate v2 and send string v2 = v + v; byte[] v2b = Encoding.UTF8.GetBytes(v2); bw.Write((byte)v2b.Length); bw.Write(v2b); bw.Flush(); // close connection br.Close(); bw.Close(); cli.Close(); } } 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(); Console.WriteLine("(connection from {0})", cli.Client.RemoteEndPoint); (new Thread((new ClientHandler(cli)).Run)).Start(); } } } }