I'm writing some code in C# for the first time which requires talking to a network attached device using HTTP. Unfortunately the device is broken and so I cannot use the
HttpWebRequest
/
HttpWebResponse
classes, so I'm having to do it myself with
TcpClient
and
NetworkStream
.
I've got the following code:
byte[] sendBytes = Encoding.ASCII.GetBytes("GET / HTTP/1.1" + Environment.NewLine + Environment.NewLine);
netStream.Write(sendBytes, 0, sendBytes.Length);
byte[] bytes = new byte[tcpClient.ReceiveBufferSize];
int bytesRead = netStream.Read(bytes, 0, tcpClient.ReceiveBufferSize);
Console.Writeline(bytesRead + " bytes read");
string returnData = Encoding.ASCII.GetString(bytes);
Console.Writeline(returnData);
Now I know for certain that my response should be 191 bytes long. However I only get 40 bytes in my
bytesRead
buffer.
The only way I can make it work is by doing this:
byte[] sendBytes = Encoding.ASCII.GetBytes("GET / HTTP/1.1" + Environment.NewLine + Environment.NewLine);
netStream.Write(sendBytes, 0, sendBytes.Length);
Thread.Sleep(50)
byte[] bytes = new byte[tcpClient.ReceiveBufferSize];
int bytesRead = netStream.Read(bytes, 0, tcpClient.ReceiveBufferSize);
Console.Writeline(bytesRead + " bytes read");
string returnData = Encoding.ASCII.GetString(bytes);
Console.Writeline(returnData)
Clearly this is ugly and is not robust to different network conditions, so I would like a way to avoid it.
I've tried various things like looping on
netStream.DataAvailable
and appending any further data but this doesn't get me any further.
Unless I have misinterpreted it, the following sentence from the
NetworkStream
documentation implies that this kind of messing around isn't necessary:
Read and write operations can be performed simultaneously on an instance of the NetworkStream
class without the need for synchronization. As long as there is one unique thread for the write operations and one unique thread for the read operations, there will be no cross-interference between read and write threads and no synchronization is required.
Will anybody suggest an alternative?