tcp client in vb.net not receiving the entire data

2019-08-10 01:08发布

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)

4条回答
可以哭但决不认输i
2楼-- · 2019-08-10 01:23

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

查看更多
Deceive 欺骗
3楼-- · 2019-08-10 01:24

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

查看更多
Melony?
4楼-- · 2019-08-10 01:35

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

查看更多
相关推荐>>
5楼-- · 2019-08-10 01:37

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)
查看更多
登录 后发表回答