' 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.Collections
Imports System.Collections.Generic
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
        Public Delegate Sub EventHandler(s As Socket, sel As IList, h As IDictionary(Of Socket, EventHandler))
        Public Shared Sub AcceptHandler(ss As Socket, sel As IList, h As IDictionary(Of Socket, EventHandler))
            ' accept connection
            Dim s As Socket = ss.Accept()
            Console.WriteLine("(connection from {0})", s.RemoteEndPoint)
            ' next handler
            sel.Add(s)
            h(s) = AddressOf ReceiveIntegerHandler
        End Sub
        Public Shared Sub ReceiveIntegerHandler(s As Socket, sel As IList, h As IDictionary(Of Socket, EventHandler))
            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))
            ' next handler
            h(s) = AddressOf ReceiveStringHandler
        End Sub
        Public Shared Sub ReceiveStringHandler(s As Socket, sel As IList, h As IDictionary(Of Socket, EventHandler))
            Dim buf As Byte()
            Dim ix As Integer
            ' 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()
            ' next handler
            sel.Remove(s)
            h.Remove(s)
        End Sub
        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)
            Dim sel As IList = New ArrayList()
            Dim h As IDictionary(Of Socket, EventHandler) = New Dictionary(Of Socket, EventHandler)()
            sel.Add(ss)
            h.Add(ss, AddressOf AcceptHandler)
            While True
                ' select
                Dim sav As IList = New ArrayList(sel)
                Socket.[Select](sel, Nothing, Nothing, 1000000)
                For Each s As Socket In sel
                    h(s)(s, sav, h)
                Next
                sel = sav
            End While
        End Sub
    End Class
End Namespace
