' Collection of code snippets by Arne Vajhøj 
' (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) 
﻿Imports System
Imports System.Security.Cryptography.X509Certificates
Imports System.IO
Imports System.Net
Imports System.Net.Security
Imports System.Net.Sockets
Imports System.Security.Authentication
Imports System.Threading

Namespace SocketDemo.Text.SecureHigh.MultiServer
    Public Class Program
        Private Class ClientHandler
            Private cli As TcpClient
            Public Sub New(cli As TcpClient)
                Me.cli = cli
            End Sub
            Public Sub Run()
                Console.WriteLine("(handler in thread {0})", Thread.CurrentThread.ManagedThreadId)
                ' get reader and writer
                Dim stm As NetworkStream = cli.GetStream()
                Dim sslstm As New SslStream(stm)
                Dim cert As X509Certificate = New X509Certificate2("\work\sslserver.pfx", "topsecret")
                sslstm.AuthenticateAsServer(cert, False, SslProtocols.Tls12, True)
                Dim sr As New StreamReader(sslstm)
                Dim sw As New StreamWriter(sslstm)
                ' read a and b
                Dim line As String = sr.ReadLine()
                Dim parts As String() = line.Split(" "C)
                Dim a As Integer = Integer.Parse(parts(0))
                Dim b As Integer = Integer.Parse(parts(1))
                ' calculate c and send
                Dim c As Integer = a + b
                sw.WriteLine(c)
                sw.Flush()
                ' read v
                Dim v As String = sr.ReadLine()
                ' calculate v2 and send
                Dim v2 As String = v & v
                sw.WriteLine(v2)
                sw.Flush()
                ' close connection
                sr.Close()
                sw.Close()
                cli.Close()
            End Sub
        End Class
        Private Const PORT As Integer = 12345
        Private Const BACKLOG As Integer = 100
        Public Shared Sub Main(args As String())
            ' listen on port
            Dim srv As New TcpListener(IPAddress.Any, PORT)
            srv.Start(BACKLOG)
            While True
                ' accept connection
                Dim cli As TcpClient = srv.AcceptTcpClient()
                Console.WriteLine("(connection from {0})", cli.Client.RemoteEndPoint)
                Dim t As Thread = New Thread(AddressOf (New ClientHandler(cli)).Run)
                t.Start()
            End While
        End Sub
    End Class
End Namespace
