2
votes

This question is very simple. Read the documentation about NetworkStream Read and I quote:

Returns Int32 The number of bytes read from the NetworkStream, or 0 if the socket is closed.

And later

IOException The underlying Socket is closed.

Which is true? Clearly both can not be true at the same time, there must be a difference. (It seems that the former is true)

1

1 Answers

3
votes

Both

If the client socket (which binded with the NetworkStream) is closed before you call Read, it throws an IO exeption.

If the server socket is closed during (or before) Read, it may return 0, that means the server sent nothing.

Some examples:

var server = new Socket(SocketType.Stream, ProtocolType.Tcp);
var client = new Socket(SocketType.Stream, ProtocolType.Tcp);

/* Init the server socket */
server.Bind(new IPEndPoint(IPAddress.Any, 19998));
server.Listen(50);
server.BeginAccept(ar =>
{
    var server2 = server.EndAccept(ar);
    //server2.Close(); // Read will return 0
},
null);

/* Init the client socket */
client.Connect(IPAddress.Loopback, 19998);
NetworkStream stream = new NetworkStream(client);
//client.Close(); // Read will throw IOException
var buf = new byte[128];
int read = stream.Read(buf, 0, 128);