Vb.net VB原始TCP只读读取前5个字节
我有一个具有以下函数的类,它打开到服务器的连接,向它发送一个原始字节字符串,然后读取响应。响应的长度为23字节,我已经通过在超级终端中发送相同的初始消息并在那里查看响应来确认服务器正在发送响应 但是,在VB.NET windows窗体应用程序中,数据保存到响应中。数据看起来只有5个字节长,然后连接超时(我有stream.ReadTimeout=1000)。。。有人知道为什么会这样吗Vb.net VB原始TCP只读读取前5个字节,vb.net,stream,tcpclient,Vb.net,Stream,Tcpclient,我有一个具有以下函数的类,它打开到服务器的连接,向它发送一个原始字节字符串,然后读取响应。响应的长度为23字节,我已经通过在超级终端中发送相同的初始消息并在那里查看响应来确认服务器正在发送响应 但是,在VB.NET windows窗体应用程序中,数据保存到响应中。数据看起来只有5个字节长,然后连接超时(我有stream.ReadTimeout=1000)。。。有人知道为什么会这样吗 Public Function sendCommand(command As String) As Boolea
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
更新:此后,我使用了一个作用域来检查将响应数据提供给服务器的串行线-当我使用超级终端时,一切看起来都正常,但奇怪的是,当我运行VB时,只有5个字符被提供给服务器,就好像服务器将串行线保持在高位,以防止任何进一步的数据被发送给它一样。我需要检查服务器的设置,但我认为这仍然是我的VB的一个问题,因为它适用于超级终端-我的VB中是否有一些TCP确认操作或我可能缺少的东西???与您发布的代码,
Response.Data
的字节数永远不会超过5个,因为这是调用stm.Read
将分配给numRead
的最大数字。我想您需要的是ofst
(您可能需要在读取流之后而不是之前增加它)。我添加的ASCII 0x04字符代码字节是EOT字符
TcpClient实际上指示传输结束,而不是像终端客户端那样将其作为原始字节发送,值为0x04
由于传输命令的方式,这意味着在第一个数据包中传输了足够多的命令,以便服务器开始返回数据,即前5个字节。
但是EOT在第二个数据包中,因此服务器停止发送更多数据
Wireshark告诉我的 你说得对,但它显示的还是前5个字符。。。请参阅我的更新