' 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.Security
Imports System.Net.Sockets
Imports System.Security.Authentication

Namespace SocketDemo.Text.SecureHigh.Client
    Public Class Program
        Private Shared Function CertCheck(sender As Object, certificate As X509Certificate, chain As X509Chain, sslPolicyErrors As SslPolicyErrors) As Boolean
            Console.WriteLine("(server is {0})", certificate.Subject)
            Return True
        End Function
        Private Const HOST As String = "localhost"
        Private Const PORT As Integer = 12345
        Public Shared Sub Main(args As String())
            ' open connection
            Dim cli As New TcpClient(HOST, PORT)
            ' get reader and writer
            Dim stm As NetworkStream = cli.GetStream()
            Dim sslstm As New SslStream(stm, False, AddressOf CertCheck)
            sslstm.AuthenticateAsClient("CN=Arne Vajhoej,OU=Demo,O=Personal,L=Coventry,ST=RI,C=US", Nothing, SslProtocols.Tls12, True)
            Dim sr As New StreamReader(sslstm)
            Dim sw As New StreamWriter(sslstm)
            Console.WriteLine("(connected)")
            ' send a and b
            Dim a As Integer = 123
            Dim b As Integer = 456
            sw.WriteLine(a & " " & b)
            sw.Flush()
            ' receive c and print
            Dim c As Integer = Integer.Parse(sr.ReadLine())
            Console.WriteLine(c)
            ' send v
            Dim v As String = "ABC"
            sw.WriteLine(v)
            sw.Flush()
            ' receive v2 and print
            Dim v2 As String = sr.ReadLine()
            Console.WriteLine(v2)
            ' close connection
            sr.Close()
            sw.Close()
            cli.Close()
            Console.ReadKey()
        End Sub
    End Class
End Namespace
