C# TcpClient在连接成功后无法检测连接状态,即使对方关闭了网络连接。以下扩展可检测连接状态:
1
2
3
4
5
|
public
static
class
TcpClientEx {
public
static
bool
IsOnline(
this
TcpClient c) {
return
!((c.Client.Poll(1000, SelectMode.SelectRead) && (c.Client.Available == 0)) || !c.Client.Connected);
}
}
|
NetworkStream的Read方法在关闭连接时会抛异常(IOException)。但是它会将线程阻塞。如果不想陷入阻塞状态,就只能通过上面的方法检测了!在读取网络流之前最好检测一下NetworkStream.DataAvailable有数据再读。
1
2
3
4
5
6
7
8
9
10
|
var
conn=state
as
TcpClient;
while
(conn.IsOnline()){
//当网络连接未中断时循环
using
(
var
s = conn.GetStream()){
var
buff=
new
byte
[512];
if
(s.DataAvailable){
//判断有数据再读,否则Read会阻塞线程。后面的业务逻辑无法处理
var
len = s.Read(buff,0,buff.Length);
}
//略...
}
}
|