It seems that the HttpWebRequest is just very slow.
The funny thing: I implemented my own HTTP client using Sockets, and I found the key to why HttpWebRequest is so slow. If I encoded ASCII headers into my own byte array and sent them to a stream, followed by an array of bytes encoded from my data, my Sockets based HTTP client behaved exactly like HttpWebRequest: first it fills one buffer with data (part of the header), then it partially uses another buffer (the rest of the header), waits 200 ms and then sends the rest of the data.
The code:
TcpClient client = new TcpClient(server, port); NetworkStream stream = client.GetStream(); // Send this out stream.Write(headerData, 0, headerData.Length); stream.Write(bodyData, 0, bodyData.Length); stream.Flush();
The solution, of course, was to add two byte arrays before sending them to the stream. My application now behaves as expected.
Code with a single write stream:
TcpClient client = new TcpClient(server, port); NetworkStream stream = client.GetStream(); var totalData = new byte[headerBytes.Length + bodyData.Length]; Array.Copy(headerBytes,totalData,headerBytes.Length); Array.Copy(bodyData,0,totalData,headerBytes.Length,bodyData.Length);
And the HttpWebRequest seems to send the header before I write to the request stream, so it can be implemented as my first code example. Does that make sense at all?
Hope this helps anyone who has the same problem!
source share