Imports System.IO
Imports System.Net
Imports System.Net.NetworkInformation
Imports System.Net.Sockets
Imports Newtonsoft.Json.Linq

Public Class TCPManager
    Inherits ConnectionManagerBase

    Private ReadOnly listener As TcpListener
    Public Property BufferSize As Integer = 10240

    Public Sub New(port As Integer)
        MyBase.New(port)
        listener = New TcpListener(IPAddress.Any, port)
    End Sub

    Public Overrides Sub Start()
        If Not IsListening Then
            listener.Start()
            IsListening = True
            Task.Run(AddressOf CheckRetriveData)
        End If
    End Sub

    Public Overrides Sub [Stop]()
        If IsListening Then
            IsListening = False
            listener.Stop()
        End If
    End Sub

    Protected Overrides Function GetBufferSize() As Integer
        Return BufferSize
    End Function

    Private Sub CheckRetriveData()
        Do While IsListening
            If listener.Pending Then
                Dim tcp As TcpClient = listener.AcceptTcpClient()
                Dim ip As String = CType(tcp.Client.RemoteEndPoint, IPEndPoint).Address.ToString
                Dim Stream As NetworkStream = tcp.GetStream
                Dim buf As Byte() = New Byte(BufferSize - 1) {}

                tcp.ReceiveBufferSize = BufferSize
                Stream.Read(buf, 0, buf.Length)

                tcp.Close()

                ProcessRetrivedData(ip, buf)
            End If
        Loop
    End Sub

    Protected Overrides Sub SendData(ep As IPEndPoint, buf As Byte())
        Dim tcp As New TcpClient

        tcp.SendBufferSize = BufferSize
        tcp.Connect(ep)

        Dim stream As NetworkStream = tcp.GetStream()

        'Send Data
        stream.Write(buf, 0, buf.Length)
        stream.Flush()

        tcp.Client.Shutdown(SocketShutdown.Both)
        tcp.Close()
    End Sub

End Class
