本文介绍了无法判断TcpListener套接字是否仍然连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用TcpListener来判断客户端是否已使用以下代码关闭连接(基于 http://msdn.microsoft.com/en-us/library/system.net.sockets.socket.connected.aspx ),但它不起作用:

 static void Main(string [] args)
{


IPAddress ipAddress = GetIP();
System.Net.Sockets.TcpListener listener = new System.Net.Sockets.TcpListener(ipAddress,8888);
listener.Start();
while(!listener.Pending());
System.Net.Sockets.Socket mySocket = listener.AcceptSocket();
Console.WriteLine(" Connected");
bool runFlag = true;
while(runFlag){
try
{
byte [] tmp = new byte [1];
mySocket.Blocking = false;
mySocket.Send(tmp,0,0);
}
catch(SocketException e)
{
if(e.NativeErrorCode.Equals(10035))// WSAEWOULDBLOCK
Console.WriteLine(" Still Connected,但发送会阻止");
else
{
Console.WriteLine(" Disconnected:error code {0}!",e.NativeErrorCode);
runFlag = false;
}
}
}
mySocket.Close();
listener.Stop();
}


有了这个我可以成功telnet到端口8888,但当我发出^]关闭时,程序无法告诉连接已经关闭。有人可以提供帮助吗?

提前致谢,

Juan Herera

解决方案

I'm trying to have a TcpListener tell if a client has closed a connection with the code below (based on http://msdn.microsoft.com/en-us/library/system.net.sockets.socket.connected.aspx), but it doesn't work:

static void Main(string[] args)
{


IPAddress ipAddress=GetIP(); System.Net.Sockets.TcpListener listener = new System.Net.Sockets.TcpListener(ipAddress, 8888); listener.Start(); while(!listener.Pending()); System.Net.Sockets.Socket mySocket = listener.AcceptSocket(); Console.WriteLine("Connected"); bool runFlag = true; while(runFlag) { try { byte[] tmp = new byte[1]; mySocket.Blocking = false; mySocket.Send(tmp, 0, 0); } catch (SocketException e) { if (e.NativeErrorCode.Equals(10035)) // WSAEWOULDBLOCK Console.WriteLine("Still Connected, but the Send would block"); else { Console.WriteLine("Disconnected: error code {0}!", e.NativeErrorCode); runFlag = false; } } } mySocket.Close(); listener.Stop(); }

With this I can successfully telnet to port 8888, but when I issue ^] close, the program can't tell the connection has been closed. Could someone help?

Thanks in advance,

Juan Herrera

解决方案


这篇关于无法判断TcpListener套接字是否仍然连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-15 23:09