客户端与服务器端TCP连接,关闭连接时应作的处理
客户端与服务器端通过TCP连接,客户端主动关闭连接时,会向服务器端发送一条信息,内容为null,据此,可在服务器端监听线程中如下处理:
if (acceptSocket.Poll (-1, SelectMode.SelectRead ))
{
if (acceptSocket.Available > 0)
{
tcpData.recSize = acceptSocket.Receive (tcpData.recData);
tcpData.sendSocket = acceptSocket;
tcpData.remoteEP = acceptSocket.RemoteEndPoint ;
ThreadPool.QueueUserWorkItem (new WaitCallback (ProcessTCPData), tcpData);
}
else
{
// 客户端关闭Socket时
acceptSocket.Shutdown (SocketShutdown.Both );
acceptSocket.Close ();
strTemp = "\r\n关闭连接:" + strIP + ":" + strPort;
this.Invoke (new AddInfoDelegate (this.AddCMDInfo), new object [] {strTemp});
break;
}
}
{
if (acceptSocket.Available > 0)
{
tcpData.recSize = acceptSocket.Receive (tcpData.recData);
tcpData.sendSocket = acceptSocket;
tcpData.remoteEP = acceptSocket.RemoteEndPoint ;
ThreadPool.QueueUserWorkItem (new WaitCallback (ProcessTCPData), tcpData);
}
else
{
// 客户端关闭Socket时
acceptSocket.Shutdown (SocketShutdown.Both );
acceptSocket.Close ();
strTemp = "\r\n关闭连接:" + strIP + ":" + strPort;
this.Invoke (new AddInfoDelegate (this.AddCMDInfo), new object [] {strTemp});
break;
}
}
若想在服务器端关闭已与某个客户端建立连接的Socket,如下操作:
acceptSocket.Shutdown (SocketShutdown.Both );
acceptSocket.Close ();
acceptSocket.Close ();
但会引发异常,故应在该Socket的监听线程中作如下处理:
while (true)
{
try
{
if (acceptSocket.Poll (-1, SelectMode.SelectRead ))
{
if (acceptSocket.Available > 0)
{
tcpData.recSize = acceptSocket.Receive (tcpData.recData);
tcpData.sendSocket = acceptSocket;
tcpData.remoteEP = acceptSocket.RemoteEndPoint ;
ThreadPool.QueueUserWorkItem (new WaitCallback (ProcessTCPData), tcpData);
}
else
{
// 对方关闭Socket时
acceptSocket.Shutdown (SocketShutdown.Both );
acceptSocket.Close ();
strTemp = "\r\n关闭连接:" + strIP + ":" + strPort;
this.Invoke (new AddInfoDelegate (this.AddCMDInfo), new object [] {strTemp});
break;
}
}
}
catch
{
// 服务器端关闭Socket时
strTemp = "\r\n关闭连接:" + strIP + ":" + strPort;
this.Invoke (new AddInfoDelegate (this.AddCMDInfo), new object [] {strTemp});
break;
}
}
{
try
{
if (acceptSocket.Poll (-1, SelectMode.SelectRead ))
{
if (acceptSocket.Available > 0)
{
tcpData.recSize = acceptSocket.Receive (tcpData.recData);
tcpData.sendSocket = acceptSocket;
tcpData.remoteEP = acceptSocket.RemoteEndPoint ;
ThreadPool.QueueUserWorkItem (new WaitCallback (ProcessTCPData), tcpData);
}
else
{
// 对方关闭Socket时
acceptSocket.Shutdown (SocketShutdown.Both );
acceptSocket.Close ();
strTemp = "\r\n关闭连接:" + strIP + ":" + strPort;
this.Invoke (new AddInfoDelegate (this.AddCMDInfo), new object [] {strTemp});
break;
}
}
}
catch
{
// 服务器端关闭Socket时
strTemp = "\r\n关闭连接:" + strIP + ":" + strPort;
this.Invoke (new AddInfoDelegate (this.AddCMDInfo), new object [] {strTemp});
break;
}
}
posted on 2005-11-30 13:57 bartholomew 阅读(1178) 评论(0) 编辑 收藏 举报