none
Read and evaluate data from NetworkStream

    Domanda

  • I have a device that is continuously sending text over a TCP port and I want to write a VB.net application that will read and evaluate this data. Each line of text that arrives over the port can be of varying length and each value in the line is separated by a comma. I need to separate out these values in order to take various actions based on their contents.

    The following code appears to read the NetworkStream fine but when I try to read the data into an array and output one field into a text file the code is only catching a few lines of the high number coming through the port.

    I assume the data is coming through too quickly and I am not catching it correctly. I am new to programming and hoping someone can tell me where I am going wrong. Any help/suggestions are much appreciated!

    Sub Main()
        Const BUFFER_SIZE As Integer = 10240
        Dim bytesToRead(BUFFER_SIZE) As Byte
        Dim tcpClient As New System.Net.Sockets.TcpClient()
        tcpClient.Connect("127.0.0.1", 2112)
        Dim networkStream As NetworkStream = tcpClient.GetStream()
        Dim textReceived As String
        Dim textReceivedArr() As String
    
        Do
          Dim numBytesRead As Integer = networkStream.Read(bytesToRead, 0, BUFFER_SIZE)
    
          ' Separate each value into an array.
          textReceived = Encoding.ASCII.GetString(bytesToRead, 0, numBytesRead)
          textReceivedArr = textReceived.Split(",")
    
          ' Display data stream.
          Console.WriteLine(Encoding.ASCII.GetString(bytesToRead, 0, numBytesRead))
    
          ' Write the 5th value in the array to a file (This is where I have the problem).
          Dim objFile As New StreamWriter("c:\temp\Output.txt", True)
          objFile.WriteLine(textReceivedArr(4))
          objFile.Close()
    
        Loop
      End Sub
    

    lunedì 18 aprile 2011 01:53

Tutte le risposte