套接字关闭时读取网络流

Network stream read when socket is closed

这道题很简单。阅读 documentation about NetworkStream Read 并引用:

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

以后

IOException The underlying Socket is closed.

哪个是真的?显然两者不能同时为真,必须有区别。 (好像前者是真的)

两者都

如果 客户端套接字 (与 NetworkStream 绑定)在您调用 Read 之前关闭,它会抛出 IO 异常。

如果 服务器套接字 Read 期间(或之前)关闭,它可能 return 0,这意味着服务器没有发送任何内容。

一些例子:

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);