I have a class that inherits from TcpClient. In that class I have a method to process responses. In that method I call I get the NetworkStream with MyBase.GetStream and call Read on it.
This works fine, excpet the first call to read blocks too long. And by too long I mean that the socket has recieved plenty of data, but won't read it until some arbitrary limit is reached. I can see that it has recieved plenty of data using the packet sniffer WireShark.
I have set the recieve buffer to small amounts, and very small amounts (like just a few bytes) to no avail. I have done the same with the buffer byte array I pass to the read method, and it still delays.
Or to put it another way. I am download 600k. The download takes 5 seconds (at a little over 100k/second connection to the server which makes sense). The initial Read call takes 2-3 seconds and tells me only 256 bytes are availble (256 is the Recieve buffer and the size of the array I read in to). Then magically, the other few hundred thousand bytes can be read in 256 byte chunks in only a few process ticks each.开发者_如何学Python Using a packet sniffer, I know that during those initial 2-3 seconds, the socket has recieved much more than just 256 bytes. My connection wasn't .25k/second for 3 seconds and then 400k for 2 seconds.
How do I get the bytes from a socket as they come in?
I had a similar issue when writing an open source C# network library. Try setting:
tcpClient.NoDelay = true;
tcpClient.Client.NoDelay = true;
This disables the nagle algorithm operating by default. This causes all sorts of random delays, deliberately, when sending and receiving very small amounts of data.
I've encountered this a few times before too, and it seems to have to do with checking up on the machine's Internet Explorer settings (proxy settings/LAN settings etc etc) which caused the 2-3 seconds delay.
Classes inside the System.Net namespace (i.e. WebClient, HttpWebRequest) seems to do this automatically on the first request.
You can try turning off or changing IE's proxy settings/LAN settings particularly the automatic settings detection option, it may help.
If that doesn't help, take a look at this article: Mysterious delay on first use of HttpWebRequest.GetRequestStream. It's not exactly the TcpClient but I think it's the same problem.
Hope this helps.
精彩评论