tcp client in vb.net not receiving the entire data response data from server

℡╲_俬逩灬. 提交于 2019-12-11 07:48:17

问题


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)


回答1:


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).




回答2:


An easy way to read a given number of bytes, is to just wrap the stream in a BinaryReader, and call ReadBytes:

Dim reader As BinaryReader = new BinaryReader(serverStream)
Dim buffer As Byte() = reader.ReadBytes(amount)



回答3:


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




回答4:


You may use tcpClient.GetStream.DataAvailable option with do while.
Increasing timer is not a correct option.



来源:https://stackoverflow.com/questions/5713547/tcp-client-in-vb-net-not-receiving-the-entire-data-response-data-from-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!