Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>No, it will not block. The Read operation reads as much data as is available, up to the number of bytes specified by the size parameter. Source: <a href="http://msdn.microsoft.com/en-us/library/system.net.sockets.networkstream.read.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/system.net.sockets.networkstream.read.aspx</a></p> <p>Given it will not wait for that extra 1 byte, if you are expecting it, you should implement a loop to continue reading the stream. You can exit the loop however you feel best.</p> <hr> <p>UPDATE: I was wrong when I stated "There's no blocking at all. If no data is available for reading, the Read method returns 0", but <strong>I was correct when I stated that it wouldn't block waiting to fill the entire buffer</strong> which it the scenario described in Kazoom's question.</p> <p>Updated to demonstrate that NetworkStream.Read blocks waiting for the first byte, but <strong>does not block waiting to fill the entire buffer</strong>.</p> <p>Create to console projects</p> <p>On one end, you have the listener:</p> <pre><code> IPEndPoint ep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 12345); TcpListener listener = new TcpListener(ep); listener.Start(); TcpClient client = listener.AcceptTcpClient(); NetworkStream s = client.GetStream(); byte[] buffer = new byte[32]; Console.WriteLine(s.Read(buffer, 0, 32)); Console.WriteLine("Press any key to continue..."); Console.Read(); </code></pre> <p>On the other end, we send only one byte:</p> <pre><code> IPEndPoint ep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 12345); TcpClient client = new TcpClient(); client.Connect(ep); client.GetStream().Write(new byte[] { 60 }, 0, 1); Console.WriteLine("Press any key to continue..."); Console.Read(); </code></pre> <p>Both sides will run until they reach Console.Read(). Notice that the listener does not block on Read.</p> <p>The listener will print "1"</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload