vb.net中的tcp客户端没有从服务器接收到完整的数据响应数据
我有一个小程序,它是一个tcp客户端。我通过以太网将字符串从该客户端发送到设备(它充当 TCP 服务器)。一旦设备收到输入字符串,它就会用响应数据进行响应。我的问题是我没有从服务器返回整个响应数据。 (设备)。
Dim serverStream As NetworkStream = clientSocket2.GetStream()
Dim outStream As Byte() = System.Text.Encoding.ASCII.GetBytes("my-cmd")
serverStream.Write(outStream, 0, outStream.Length)
'serverStream.Flush()
Dim inStream(clientSocket2.ReceiveBufferSize) As Byte
serverStream.Read(inStream, 0, CInt(clientSocket2.ReceiveBufferSize))
returndata = System.Text.Encoding.ASCII.GetString(instream)
返回数据没有从服务器(设备)返回的完整响应
I have a small program which is a tcp client. I send a string from this client to a device over ethernet (it acts as the tcp server). As soon as the device recieves the input string it will respond back with response data. My problem is i am not getting the entire response data back from the server. (device).
Dim serverStream As NetworkStream = clientSocket2.GetStream()
Dim outStream As Byte() = System.Text.Encoding.ASCII.GetBytes("my-cmd")
serverStream.Write(outStream, 0, outStream.Length)
'serverStream.Flush()
Dim inStream(clientSocket2.ReceiveBufferSize) As Byte
serverStream.Read(inStream, 0, CInt(clientSocket2.ReceiveBufferSize))
returndata = System.Text.Encoding.ASCII.GetString(instream)
Returndata does not have the full response back from the server(device)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
通过网络发送的任何数据都可能被分段。 TCP 不保证在一个块中完成传输。
要接收整个消息,可能需要多次读取。
我没有检查您的代码,因为它当前尚未格式化。请这样做(以便我们更轻松地为您提供帮助)。
Any data sent over a network may be fragmented. TCP does not guarantee complete transmission in one block.
To receive the whole message multiple reads may be necessary.
I did not check your code since it is currently not formatted. Please do so (in order to make it easier for us to help you).
读取给定字节数的一种简单方法是将流包装在
BinaryReader
中,然后调用ReadBytes
:An easy way to read a given number of bytes, is to just wrap the stream in a
BinaryReader
, and callReadBytes
:其实很简单。我只是在阅读流之前延迟了一些时间。问题在于,在读取整个流之前,程序执行到了下一行。一点延迟可确保检索整个数据流。无论如何,谢谢
Actually it was very simple. I just gave some delay before reading the stream. The problem was that before the entire stream could be read the program execution came to the next line. A little delay made sure that the entire stream of data is retrieved. Thanks anyway
您可以将
tcpClient.GetStream.DataAvailable
选项与 do while 一起使用。增加计时器不是正确的选择。
You may use
tcpClient.GetStream.DataAvailable
option with do while.Increasing timer is not a correct option.