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

Namespace SocketDemo.Binary.Low.AsyncAwaitServer
    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 Shared running As Integer = 0
        Private Shared Async Sub Process(ss As Socket)
            Interlocked.Increment(running)
            ' accept connection async
            Dim s As Socket = Await ss.AcceptAsync()
            Console.WriteLine("(connection from {0})", s.RemoteEndPoint)
            ' read a and b
            Dim buf As Byte() = New Byte(3) {}
            Await s.ReceiveAsync(buf)
            Dim a As Integer = BytesToInt(buf)
            buf = New [Byte](3) {}
            Await s.ReceiveAsync(buf)
            Dim b As Integer = BytesToInt(buf)
            ' calculate c and send
            Dim c As Integer = a + b
            s.Send(IntToBytes(c))
            ' read v
            buf = New Byte(0) {}
            Await s.ReceiveAsync(buf)
            Dim buflen As Integer = buf(0)
            buf = New Byte(buflen - 1) {}
            Await s.ReceiveAsync(buf)
            Dim v As String = Encoding.UTF8.GetString(buf)
            ' calculate v2 and send
            Dim v2 As String = v & v
            Dim v2b As Byte() = Encoding.UTF8.GetBytes(v2)
            s.Send(New Byte() {CByte(v2b.Length)})
            s.Send(v2b)
            ' close connection
            s.Close()
            Interlocked.Decrement(running)
        End Sub
        Private Const PORT As Integer = 12345
        Private Const BACKLOG As Integer = 100
        Private Const NTHREADS As Integer = 10
        Public Shared Sub Main(args As String())
            ' listen on port
            Dim ss As New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
            ss.Bind(New IPEndPoint(IPAddress.Any, PORT))
            ss.Listen(BACKLOG)
            While True
                Process(ss)
                While running >= NTHREADS
                    Thread.Yield()
                End While
            End While
        End Sub
    End Class
End Namespace
