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)
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).
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)
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
You may use tcpClient.GetStream.DataAvailable
option with do while.
Increasing timer is not a correct option.