如何在tcp服务器中实现断开代码

时间:2018-04-17 10:08:53

标签: c# try-catch chat tcplistener

所以我创建了一些代码,可以帮助我在客户端断开连接时显示断开连接的消息但是我不确定在哪里放置代码。目前我把它放在我的catch块howerver中,它每次调用catch块时都会运行。以下是我的代码

private void doChat()
{
    int requestCount = 0;
    byte[] bytesFrom = new byte[10025];
    string dataFromClient = null;
    string rCount = null;

    requestCount = 0;

    while (true)
    {
        try
        {
            requestCount = requestCount + 1;
            NetworkStream networkStream = clientSocket.GetStream();

            networkStream.Read(bytesFrom, 0, (int)clientSocket.ReceiveBufferSize);

            dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom);
            dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("$"));

            Console.WriteLine("From client - " + clNo + " : " + dataFromClient);
            rCount = Convert.ToString(requestCount);
            //ConnUsers.Add(clNo);
            Program.broadcast(dataFromClient, clNo, true);                 
        }
        catch (Exception ex)
        {
            Console.WriteLine(clNo + " Disconnected!");
            ConnUsers.Remove(clNo);
            clientsList.Remove(dataFromClient);
            foreach (var name in ConnUsers)
            {
                Console.WriteLine("Current Connected Users : " + string.Join(",", name));
            }
            //Console.WriteLine
            break;
        }
    }//end while
}//end doChat

我希望能够在我的try块中调用下面的代码,以便任何catch异常都不会触发代码。

Console.WriteLine(clNo + " Disconnected!");
ConnUsers.Remove(clNo);
clientsList.Remove(dataFromClient);
foreach (var name in ConnUsers)
{
    Console.WriteLine("Current Connected Users : " + string.Join(",", name));
}
//Console.WriteLine
break;

我遇到这个问题,其中调用了else块,并在catch块被触发后直接调用。这是糟糕的编码,但我想知道一种更合适的方法将代码放在我的catch块中,以便它正常运行。

1 个答案:

答案 0 :(得分:0)

尝试使用System.ArgumentOutOfRangeException,而不是一般的Exception。

catch (ArgumentOutOfRangeException ex)
    {
        Console.WriteLine(clNo + " Disconnected!");
        ConnUsers.Remove(clNo);
        clientsList.Remove(dataFromClient);
        foreach (var name in ConnUsers)
        {
            Console.WriteLine("Current Connected Users : " + string.Join(",", name));
        }
        //Console.WriteLine
        break;
    }