0

我有一个带有以下函数的类,它打开到服务器的连接,向它发送一个原始字节字符串,然后读取响应。响应有 23 个字节长,我通过在超级终端中发送相同的初始消息并在那里查看响应来确认服务器正在发送响应。

但是,使用 VB.NET Windows 窗体应用程序,保存到 Response.Data 中的数据似乎只有 5 个字节长,然后连接超时(我有 stream.ReadTimeout = 1000)......谁能明白为什么这可能是案子?

 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

更新:我已经使用范围检查将响应数据提供给服务器的串行线路 - 当我使用 hyperTerm 时,一切看起来都正常,但奇怪的是,当我运行 VB 时,只有 5 个字符被提供给服务器,就像服务器一样将串行线保持为高电平,以防止向其发送任何进一步的数据。我需要检查服务器的设置,但我认为这仍然是我的 VB 的问题,因为它对 HyperTerm 来说很好 - 是否有一些 TCP ACKnowledge 操作或我的 VB 中可能缺少的东西?

4

2 回答 2

1

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!

于 2013-07-26T11:20:51.500 回答
1

使用您发布的代码,Response.Data永远不会超过 5 个字节,因为这是调用stm.Read将分配给的最大数字numRead。我认为您想要ofst(并且您可能需要在读取流之后而不是之前增加它)。

于 2013-07-17T13:22:56.617 回答