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

Namespace SocketDemo.Binary.Low.Client
    Public Class Program
        Private Shared Function IntToBytes(v As Integer) As Byte()
            Dim buf As Byte() = BitConverter.GetBytes(v)
            If BitConverter.IsLittleEndian Then
                Array.Reverse(buf)
            End If
            Return buf
        End Function
        Private Shared Function BytesToInt(buf As Byte()) As Integer
            If BitConverter.IsLittleEndian Then
                Array.Reverse(buf)
            End If
            Return BitConverter.ToInt32(buf, 0)
        End Function
        Private Const HOST As String = "localhost"
        Private Const PORT As Integer = 12345
        Public Shared Sub Main(args As String())
            ' open connection
            Dim s As New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
            s.Connect(HOST, PORT)
            Console.WriteLine("(connected)")
            Dim buf As Byte()
            Dim ix As Integer
            ' send a and b
            Dim a As Integer = 123
            Dim b As Integer = 456
            s.Send(IntToBytes(a))
            s.Send(IntToBytes(b))
            ' receive c and print
            buf = New [Byte](3) {}
            ix = 0
            While ix < buf.Length
                ix += s.Receive(buf, ix, buf.Length - ix, SocketFlags.None)
            End While
            Dim c As Integer = BytesToInt(buf)
            Console.WriteLine(c)
            ' send v
            Dim v As String = "ABC"
            Dim vb As Byte() = Encoding.UTF8.GetBytes(v)
            s.Send(New Byte() {CByte(vb.Length)})
            s.Send(vb)
            ' receive v2 and print
            buf = New [Byte](0) {}
            s.Receive(buf)
            Dim buflen As Integer = buf(0)
            buf = New Byte(buflen - 1) {}
            ix = 0
            While ix < buf.Length
                ix += s.Receive(buf, ix, buf.Length - ix, SocketFlags.None)
            End While
            Dim v2 As String = Encoding.UTF8.GetString(buf)
            Console.WriteLine(v2)
            ' close connection
            s.Close()
        End Sub
    End Class
End Namespace
