首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >VB原始TCP只读取前5个字节

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

Stack Overflow用户
提问于 2013-07-17 13:16:49
回答 2查看 533关注 0票数 0

我有一个具有以下函数的类,它打开到服务器的连接,向它发送一个原始字节字符串,然后读取响应。响应有23个字节长,我已经确认响应是由服务器发送的,方法是在HyperTerminal中发送相同的初始消息并在那里查看响应。

但是,使用VB.NET windows窗体应用程序,保存到Response.Data中的数据似乎只有5个字节长,然后连接超时(我有stream.ReadTimeout =1000).有人知道为什么会这样吗?

代码语言:javascript
复制
 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中可能缺少的东西?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-07-26 11:20:51

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

TcpClient没有像终端客户端那样以0x04作为原始字节发送出去,而是实际上表示传输的结束。

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

告诉我这件事!

票数 1
EN

Stack Overflow用户

发布于 2013-07-17 13:22:56

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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/17700837

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档