TCP通信过程中时时监测连接是否已断开
2012-05-09 09:35
239 查看
贴出主要代码:
private void ReceiveData(object cUserData)
{
User cUser=(User ) cUserData;
//连接断开标志
bool closed=false;
byte[] flagbyte=new byte [1];
while (!closed )
{
try
{
//检测是否有课接收的数据
if(cUser.client.Available>0)
{
byte[] bytes=new byte [cUser.client.Available ];
cUser.netStream.Read (bytes,0,bytes.Length );
}
//监测连接是否存在
if(cUser.client.Client.Poll (0,SelectMode.SelectRead))
closed=int.Equals(cUser.client.Client.Receive (flagbyte,SocketFlags.Peek),0);
}
catch {
closed =true;
System.Diagnostics.Debug.WriteLine ("断开连接!");
cUser.Close ();
}
Thread.Sleep (1);
}
}
public class User
{
public string cName { get; set; }
public TcpClient client { get; set; }
public NetworkStream netStream { get; set; }
public User(TcpClient _client)
{
this.client = _client;
this.netStream = client.GetStream();
}
public void Close()
{
netStream.Close();
client.Client.Close();
client.Close();
}
}
private void ReceiveData(object cUserData)
{
User cUser=(User ) cUserData;
//连接断开标志
bool closed=false;
byte[] flagbyte=new byte [1];
while (!closed )
{
try
{
//检测是否有课接收的数据
if(cUser.client.Available>0)
{
byte[] bytes=new byte [cUser.client.Available ];
cUser.netStream.Read (bytes,0,bytes.Length );
}
//监测连接是否存在
if(cUser.client.Client.Poll (0,SelectMode.SelectRead))
closed=int.Equals(cUser.client.Client.Receive (flagbyte,SocketFlags.Peek),0);
}
catch {
closed =true;
System.Diagnostics.Debug.WriteLine ("断开连接!");
cUser.Close ();
}
Thread.Sleep (1);
}
}
public class User
{
public string cName { get; set; }
public TcpClient client { get; set; }
public NetworkStream netStream { get; set; }
public User(TcpClient _client)
{
this.client = _client;
this.netStream = client.GetStream();
}
public void Close()
{
netStream.Close();
client.Client.Close();
client.Close();
}
}
相关文章推荐
- C# 中TCP连接通过数据接收来判断连接是否断开
- 网络通信之检测远端连接是否断开连接
- TCP建立连接和断开连接过程
- TCP协议连接建立与连接断开过程(含断开时的TCP状态图)
- TCP协议连接建立与连接断开过程(含断开时的TCP状态图)
- Linux socket编程入门及客户端服务器端通信实现 – 提高篇:TCP连接过程分析
- Netty4 Tcp长连接、断开重连、心跳监测、Msgpack编码解码
- Tcp 创建与断开连接过程
- Tcp服务端判断客户端是否断开连接
- 网络通信过程 及TCP/UDP 面向连接?
- tcp连接、断开过程
- tcp/udp建立连接并通信的过程
- TCP建立断开连接过程
- TCP建立连接和断开连接过程的理解
- socket ,tcp/ip连接和断开过程图解
- TCP/IP 建立连接、断开连接的过程
- Tcp服务端判断客户端是否断开连接
- 判断数据库时时连接程序,判断是否断开,断开则自动连接
- TCP连接和断开过程详解
- Tcp服务端判断客户端是否断开连接