I have a class with the below function that opens a connection to a server, sends it a raw string of bytes and then reads the response. The response is 23 bytes long and I have confirmed the response is being sent by the server by sending the same initial message in HyperTerminal and viewing the response there.
However, with the VB.NET windows form application the data saved into Response.Data only appears to be 5 bytes long and then the connection times out (I have stream.ReadTimeout = 1000)... can anyone see why this might be the case?
Public Function sendCommand(command As String) As Boolean
Dim lst As New List(Of Byte)()
Dim buf(50) As Byte
Dim numRead As Integer
Dim ofst As Integer = 0
lst.AddRange(Encoding.ASCII.GetBytes(command)) ' Convert the command string to a list of bytes
lst.Add(&H4) ' Add 0x04, 0x0A and a newline to the end of the list
lst.Add(&HA)
lst.AddRange(Encoding.ASCII.GetBytes(vbNewLine))
buf = lst.ToArray ' Convert the list to an array
If Not makeConnection() Then ' Make the connection (client & stream) and check if it can be read and written to.
Return False
End If
stm.Write(buf, 0, buf.Length) ' Write the array to the stream
Try
Do
numRead = stm.Read(buf, ofst, 5) ' Try and read the response from the stream
ofst += numRead
Loop While numRead > 0
Catch e As Exception
MessageBox.Show(e.Message)
End Try
breakConnection() ' Close the connection
Response.Type = Type.Strng ' Save the response data
Response.Data = System.Text.Encoding.ASCII.GetString(buf, 0, ofst) 'Changed to ofst
'Response.Type = Type.Int
'Response.Data = numRead.ToString
Return True
End Function
UPDATE: I have since used a scope to check the serial line that feeds the response data to the server - when I use hyperTerm everything appears OK, but strangely, when I run the VB only 5 chars are fed to the server as if the server is holding the serial line high to prevent any further data being sent to it. I will need to check out the settings of the server, but I'm thinking this is still a problem from my VB as it's fine for HyperTerm - is there some TCP ACKnowledge action or something that I might be missing in my VB??
The ASCII 0x04 character code byte I was adding is the EOT char.
Instead of sending this out as raw byte with the value 0x04 as a terminal client does, the TcpClient actually indicates an end of transmission.
Due to the way the transmitted command this meant that enough of the command was transmitted in the first packet for the server to start returning data - i.e. the first 5 bytes. But the EOT was in the second packet and so the server stopped sending any more data!!
Wireshark told me this!