Imports System.Text
Public Class LAN

    '(0)Class variable
    Private LanSocket As System.Net.Sockets.TcpClient                                   'LAN socket
    Public MsgBuf As String = ""                                                        'Received Data

    '(1)Connect
    Public Function OpenInterface(ByVal ipaddress As String, ByVal port As String) As Boolean
        Dim ret As Boolean = False
        Dim ip As System.Net.IPAddress = New System.Net.IPAddress(0)                    'IP address

        Try
            If System.Net.IPAddress.TryParse(ipaddress, ip) Then
                LanSocket = New System.Net.Sockets.TcpClient                            'Create a LAN socket object
                LanSocket.NoDelay = True
                LanSocket.Connect(ip, Convert.ToInt32(port))                            'Connect
                ret = True
            End If

        Catch Ex As Exception
            MsgBox(Ex.Message)
        End Try

        OpenInterface = ret

    End Function

    '(2)Disconnect
    Public Function CloseInterface() As Boolean
        Dim ret As Boolean = False

        Try
            LanSocket.Close()                                                           'LAN socket close
            ret = True
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try

        CloseInterface = ret
    End Function

    '(3)Send commands
    Public Function SendMsg(ByVal strMsg As String) As Boolean
        Dim ret As Boolean = False
        Dim SendBuffer(1024) As Byte

        Try
            strMsg += vbCrLf                                                            'Add a terminator, CR+LR, to transmitted command
            SendBuffer = System.Text.Encoding.Default.GetBytes(strMsg)                  'Convert to byte type
            LanSocket.GetStream().Write(SendBuffer, 0, SendBuffer.Length)               'Write data in the transmit buffer
            ret = True
        Catch Ex As Exception
            MsgBox(Ex.Message)
        End Try

        SendMsg = ret

    End Function

    '(4)Receive
    Public Function ReceiveMsg(ByVal timeout_ms As Long) As Boolean
        Dim ret As Boolean = False
        Dim ary(65535) As Byte
        Dim rcv As String
        Dim len As Integer
        Dim buf As New StringBuilder()
        Dim sw As New Stopwatch()

        Try
            MsgBuf = ""                                                                 'Clear received data

            sw.Start()                                                                  'Start a stopwatch
            'Continue the loop until LF is received
            Do
                If LanSocket.GetStream().DataAvailable = True Then
                    len = LanSocket.GetStream().Read(ary, 0, ary.Length)                'Read data from the receive buffer
                    rcv = Encoding.Default.GetString(ary).Substring(0, len)
                    rcv = rcv.Replace(vbCr, "")                                         'Delete CR in received data
                    If rcv.IndexOf(vbLf) >= 0 Then                                      'End the loop when LF is received
                        rcv = rcv.Substring(0, rcv.IndexOf(vbLf))                       'Extract data without LF and the following from the original received data
                        buf.Append(rcv)                                                 'Save the data
                        MsgBuf = buf.ToString()
                        Exit Do
                    Else
                        buf.Append(rcv)                                                 'Save the data
                    End If
                End If

                'Timeout processing
                If sw.ElapsedMilliseconds > timeout_ms Then                             'Save the data
                    MsgBuf = "Timeout"
                    MsgBox(MsgBuf)
                    ReceiveMsg = ret
                    Exit Function
                End If

            Loop
            sw.Stop()                                                                   'Stop a stopwatch
            ret = True

        Catch Ex As Exception
            MsgBuf = "Error"
            MsgBox(Ex.Message)
        End Try

        ReceiveMsg = ret

    End Function

    '(5)Transmit and receive commands
    Public Function SendQueryMsg(ByVal strMsg As String, ByVal timeout_ms As Long) As Boolean
        Dim ret As Boolean = False
        Dim ary(65535) As Byte

        If LanSocket.GetStream().DataAvailable = True Then
            LanSocket.GetStream().Read(ary, 0, ary.Length)                              'If exist the data in the receive buffer, read all data.
        End If

        ret = SendMsg(strMsg)                                                           'Transmit commands
        If ret Then
            If InStr(strMsg, "?") <> 0 Then
                ret = ReceiveMsg(timeout_ms)                                            'Receive response when command transmission is succeeded
            End If
        End If

        SendQueryMsg = ret
    End Function

End Class
