所以我正在制作一个 Tcp 服务器,当我在客户端断开连接时遇到问题时。正在引发异常,但看起来服务器看不到它。并且它不会从列表中删除断开连接的客户端。这是代码:
public void Read(IAsyncResult ar, TcpClient PL)
{
try
{
{
BytesRead[PL] = PL.GetStream().EndRead(ar);
}
if (BytesRead[PL] < 1)
{
throw new SocketException();
}
else
{
while (true)
{
packets++; break;
}
}
}
catch (Exception x)
{
if ((x.Message.Contains("Client") && x.Message.Contains("Disconnected")) || x is SocketException || x is EndOfStreamException || x is IOException) //|| x.InnerException.GetType() == typeof(IOException))
{
throw;
}
else
{
System.Console.WriteLine(x.ToString());
}
}
}
当客户端关闭程序或被任务管理器杀死时,它会发生
这是使用方法Read
的地方。
private void HandleClient(object client)
{
TcpClient tcpClient = (TcpClient)client;
NetworkStream ns = tcpClient.GetStream();
while (true)
{
try
{
while ((true))
{
{
try
{
}
catch (SocketException ex)
{
if ((ex.Message.Contains("Client") && ex.Message.Contains("Disconnected")) || ex is SocketException)
{
throw;
}
}
try
{
{
}
}
catch (Exception ex)
{
}
}
}
}
catch (SocketException ex)
{
if (((ex.Message.Contains("Client") && ex.Message.Contains("Disconnected"))) || ex is SocketException )
{
clients.Remove(tcpClient);
}
else
{
System.Console.WriteLine(ex.ToString());
}
}
}
}
这是初始化TcpListener
public void Server1()
{
timer = new Timer(new TimerCallback(MultipleCheck), null, 0, 500);
listener = new TcpListener(IPAddress.Parse("25.75.22.56"), 29339);
listenThread = new Thread(new ThreadStart(ListenForClients));
listenThread.Start();
}
这是它接受TcpClient
的方法
private void ListenForClients()
{
listener.Start();
while (true)
{
System.Console.Title = "Server : " + clients.Count.ToString();
if (!LineStarted)
{
System.Console.WriteLine("Server started on port 29339");
LineStarted = true;
}
System.Console.WriteLine("Connection Request");
TcpClient client = listener.AcceptTcpClient();
if (client.Connected)
{
clients.Add(client);
System.Console.WriteLine("New Client Connected");
//if (threads.ContainsKey(client))
{
threads[client].Start(client);
}
counter++;
}
}
}
在threads[tcpClient].Abort();
之前放置尝试说明
try
{
//Removing Client from list and notifying connected users about disconnected
//client from list
}
catch
{
}
//And after Abort the thread to avoid the exception of thread aborting being
//thrown too early
threads[tcpClient].Abort();
threads.Remove(tcpClient);