' 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

Namespace SocketDemo.Binary.Low.SingleServer
    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 PORT As Integer = 12345
        Private Const BACKLOG As Integer = 100
        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
                ' accept connection
                Dim s As Socket = ss.Accept()
                Console.WriteLine("(connection from {0})", s.RemoteEndPoint)
                Dim buf As Byte()
                Dim ix As Integer
                ' read a and b
                buf = New [Byte](3) {}
                ix = 0
                While ix < buf.Length
                    ix += s.Receive(buf, ix, buf.Length - ix, SocketFlags.None)
                End While
                Dim a As Integer = BytesToInt(buf)
                buf = New [Byte](3) {}
                ix = 0
                While ix < buf.Length
                    ix += s.Receive(buf, ix, buf.Length - ix, SocketFlags.None)
                End While
                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) {}
                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 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()
            End While
        End Sub
    End Class
End Namespace
