I have seen many times that some people call the networkstream. Flush method to immediately send data during network transmission. Indeed, calling the flush method of stream will clear the buffer, but the problem is that networkstream is not a stream with a buffer, which is described in msdn. And its source code can also be seen. Whether it is. NET 2.0 or the latest. Net 4.5, check the source code of networkstream. Flush method in ilspy and the results are the same:
This method has no effect at all.
In this case, all data sent from the network will be processed immediately? No, TCP has a Nagle algorithm. Simply put, this algorithm is used to increase the efficiency of the network system and reduce the sending frequency of small packets. That is to say, small data packets will be cached and sent out at one time when the data volume increases. Obviously, the Nagle Algorithm in TCP is inappropriate for data that needs to be processed in real time and needs to be disabled.
In. net, disable the Nagle algorithm and set the TCP option socketoptionname. nodelay to true. The Code is as follows:
// + Using system. net;
// + Using system. net. Sockets;
Socket socket;
Socket. setsocketoption (socketoptionlevel. TCP, socketoptionname. nodelay, true );
At the same time, both the socket type and the tcpclient type have a nodelay attribute. According to the description of msdn, it is indeed about disabling the Nagle algorithm. However, you can use ilspy to check the source code. It sets the value of socketoptionname. debug.
But let's look at the definitions of the socketoptionname. debug and socketoptionname. nodelay enumeration values and find that they are both 1. Therefore, the two are completely equivalent.