' 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.IO
Imports System.Net.Sockets
Imports System.Text

Namespace SocketDemo.Binary.High.Client
    Public Class Program
        Private Shared Function HTON(v As Integer) As Integer
            If BitConverter.IsLittleEndian Then
                Dim buf As Byte() = BitConverter.GetBytes(v)
                Array.Reverse(buf)
                Return BitConverter.ToInt32(buf, 0)
            Else
                Return v
            End If
        End Function
        Private Shared Function NTOH(v As Integer) As Integer
            If BitConverter.IsLittleEndian Then
                Dim buf As Byte() = BitConverter.GetBytes(v)
                Array.Reverse(buf)
                Return BitConverter.ToInt32(buf, 0)
            Else
                Return v
            End If
        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 br As New BinaryReader(stm)
            Dim bw As New BinaryWriter(stm)
            Console.WriteLine("(connected)")
            ' send a and b
            Dim a As Integer = 123
            Dim b As Integer = 456
            bw.Write(HTON(a))
            bw.Write(HTON(b))
            bw.Flush()
            ' receive c and print
            Dim c As Integer = NTOH(br.ReadInt32())
            Console.WriteLine(c)
            ' send v
            Dim v As String = "ABC"
            Dim vb As Byte() = Encoding.UTF8.GetBytes(v)
            bw.Write(CByte(vb.Length))
            bw.Write(vb)
            bw.Flush()
            ' receive v2 and print
            Dim buflen As Integer = br.ReadByte()
            Dim buf As Byte() = New Byte(buflen - 1) {}
            Dim ix As Integer = 0
            While ix < buf.Length
                ix += br.Read(buf, ix, buf.Length - ix)
            End While
            Dim v2 As String = Encoding.UTF8.GetString(buf)
            Console.WriteLine(v2)
            ' close connection
            br.Close()
            bw.Close()
            cli.Close()
        End Sub
    End Class
End Namespace
