您的位置:首页 > 理论基础 > 计算机网络

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();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: