Imports System.Net.Sockets
Imports System.Text

Namespace UTSModule.Service

    Public Class AutsTcpClient
        Implements IDisposable

        Private _tcpClient As TcpClient
        Private _tcpOpen As Boolean

        Private ReadOnly _hostName As String
        Private ReadOnly _hostPort As Integer


        Sub New(hostName As String, port As Integer)
            _hostName = hostName

            _hostPort = port

            _tcpOpen = False
        End Sub


        Public ReadOnly Property IsOpen() As Boolean
            Get
                Return _tcpOpen
            End Get
        End Property


        Public Sub Open()
            If _tcpOpen = True Then Return

            _tcpClient = New TcpClient(_hostName, _hostPort)
            _tcpOpen = True
        End Sub


        Public Sub Close()
            If _tcpOpen = False Then Return

            _tcpClient.Close()
            _tcpClient.Dispose()
            _tcpOpen = False
        End Sub


        ''' <summary>
        ''' 网络发送Json字符串,字符串以回车换行结尾
        ''' </summary>
        ''' <param name="jsonString"></param>
        Public Sub WriteJsonString(jsonString As String)
            Dim buf() As Byte = Encoding.UTF8.GetBytes(jsonString)
            _tcpClient.GetStream().Write(buf, 0, buf.Length)
        End Sub


        ''' <summary>
        ''' 超时接收回复信息,以回车换行结尾
        ''' </summary>
        ''' <param name="timeout">超时时间,单位毫秒</param>
        ''' <returns>接收到的字符串,超时返回空字符串</returns>
        Public Function ReadJsonString(Optional timeout As Integer = 1000) As String
            Dim replayStr As New StringBuilder

            Dim time As Date = Now
            While (Now - time).TotalMilliseconds < timeout
                If _tcpClient.Available > 0 Then
                    Dim length As Integer = _tcpClient.Available
                    Dim buf(length - 1) As Byte
                    _tcpClient.GetStream().Read(buf, 0, length) '读取数据

                    replayStr.Append(Encoding.UTF8.GetString(buf))

                    If replayStr.ToString().EndsWith(vbCrLf) Then '校验，以回车换行结尾
                        Exit While
                    End If
                End If
            End While

            Return replayStr.ToString()
        End Function

        Public Function Connected() As Boolean
            If _tcpClient Is Nothing Then Return False
            If _tcpClient.Client Is Nothing Then Return False
            Return _tcpClient.Connected
        End Function
        Public Sub Dispose() Implements IDisposable.Dispose
            If IsOpen() Then
                Close()
            End If
        End Sub

    End Class
End Namespace