C# TcpClient在连接成功后无法检测连接状态,即使对方关闭了网络连接。以下扩展可检测连接状态:

    1. public static class TcpClientEx
    2. {
    3. public static bool IsOnline(this TcpClient c)
    4. {
    5. return !((c.Client.Poll(1000, SelectMode.SelectRead) && (c.Client.Available == 0))
    6. || !c.Client.Connected);
    7. }
    8. }

    NetworkStream的Read方法在关闭连接时会抛异常(IOException)。但是它会将线程阻塞。如果不想陷入阻塞状态,就只能通过上面的方法检测了!在读取网络流之前最好检测一下NetworkStream.DataAvailable有数据再读。

    1. var conn=state as TcpClient;
    2. while(conn.IsOnline())
    3. {
    4. //当网络连接未中断时循环
    5. using (var s = conn.GetStream())
    6. {
    7. var buff=new byte[512];
    8. if(s.DataAvailable)
    9. {
    10. //判断有数据再读,否则Read会阻塞线程。后面的业务逻辑无法处理
    11. var len = s.Read(buff,0,buff.Length);
    12. }
    13. //略...
    14. }
    15. }