C# Networkstream.read()

后端 未结 3 1911
忘了有多久
忘了有多久 2021-02-08 11:48

How does read(buffer, offset, length) actually work, if i pass the length to read as 32, does that mean that it would keep blocking till it receives the 32 bytes?

I unde

3条回答
  •  别跟我提以往
    2021-02-08 12:20

    It will block until it receives 32 bytes, or the connection is closed. The async methods BeginRead() and EndRead() should be used to provide non-blocking reads.

    Here is some example code clearly demonstrating the blocking effect.

       Socket one = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        Socket two = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
    
        IPEndPoint ep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 12345);
    
        one.Bind(ep);
        one.Listen(1);
        two.Connect("127.0.0.1", 12345);
        one = one.Accept();
    
        NetworkStream s = new NetworkStream(two);
        byte[] buffer = new byte[32];
        s.Read(buffer, 0, 32);
    

    Edit

    Even though this code produces the blocking effect, it's only because of NetworkStream's implementation of Stream's abstract Read() method (which must be overridden). The documentation on Stream.Read() states this:

    Implementations return the number of bytes read. The return value is zero only if the position is currently at the end of the stream.

    Which is why the code blocks when NO data has been received AND the end of the stream has not been reached. It also goes on to say:

    The implementation will block until at least one byte of data can be read, in the event that no data is available. Read returns 0 only when there is no more data in the stream and no more is expected (such as a closed socket or end of file). An implementation is free to return fewer bytes than requested even if the end of the stream has not been reached.

提交回复
热议问题