Con più domande
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
Tutte le risposte
Based on my understanding, I also think your assumption maybe the reason. Please check Dave's reply in this similar thread which may make you get some ideas.
http://social.msdn.microsoft.com/Forums/en-US/ncl/thread/759f3f2f-347b-4bd8-aa05-fb7f681c3426 (NetworkStream.Read() does not always read the full string returned from the server)
If you have any concerns, please feel free to follow up.
Liliane Teng [MSFT]
MSDN Community Support | Feedback to us
Get or Request Code Sample from Microsoft
Please remember to mark the replies as answers if they help and unmark them if they provide no help.
Thanks for pointing that thread out.
I think my problem is that I am reading more than one line of the NetworkStream at a time. Each line of data can be of varying lengths. How can I just process one line at a time coming through the TCP port?
I am receiving up to about 60 lines of data at a time into my textReceived string, each line separated by a line feed and carriage return.
Could I use StreamReader to read and parse each line? How can I get StreamReader to continuously read what is coming through the socket?