VB原始TCP只读读取前5个字节



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

但是,对于VB.NET windows窗体应用程序,数据保存到响应中。数据似乎只有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来说很好——在我的VB中是否有一些TCP确认操作或我可能缺少的东西??

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

我添加的ASCII 0x04字符代码字节是EOT字符。

TcpClient实际上指示传输结束,而不是像终端客户端那样将其作为值为0x04的原始字节发送出去。

由于传输命令的方式,这意味着在第一个数据包中传输了足够多的命令,以便服务器开始返回数据,即前5个字节。但EOT在第二个数据包中,因此服务器停止发送更多数据!!

Wireshark告诉我了!

最新更新