关闭1个TCP客户端会导致所有连接的客户端“断开连接”

时间:2018-07-24 21:01:09

标签: c# tcp connection chat

我正在研究一个简单的C#TCP聊天程序。我在使用断开功能时遇到麻烦。客户端单击断开连接按钮后,它将成功离开服务器,并且服务器发送“ [客户端]已离开服务器”。所有其他连接的客户端。但是,当另一个连接的客户端发送消息时,它将引发异常:System.InvalidOperationException: The operation is not allowed on non-connected sockets.。是什么导致这种情况发生?

我已经看了半个小时的代码,不知道是什么原因造成的。

客户端处理程序类:

public class handleClinet
{
    TcpClient clientSocket;
    string clNo;
    Hashtable clientsList;

    public void startClient(TcpClient inClientSocket, string clineNo, Hashtable cList)
    {
        this.clientSocket = inClientSocket;
        this.clNo = clineNo;
        this.clientsList = cList;
        Thread ctThread = new Thread(doChat);
        ctThread.Start();
    }

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




        try{
            while (Server.isOnline = true)
            {

                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("Message from " + clNo + ": " + dataFromClient);
                rCount = Convert.ToString(requestCount);

                Server.broadcast (dataFromClient, clNo, true);


            }
        } catch (Exception ex){

                Console.ForegroundColor = ConsoleColor.Yellow;
                Server.broadcast(clNo + " has left the server.", clNo, false);
                Console.WriteLine(clNo + " has left the server.");
                Disconnect(clNo);
        }
   }

    void Disconnect(string user){

        TcpClient dicl;
        dicl = (TcpClient)clientsList[user];


        if(dicl.Client.Connected == false){


            dicl.Close();
            clientsList.Remove(user);

        }

    }
}

客户端断开按钮代码:

 // Disconnect from server.
 public static void Disconnect(){



     serverStream.Close();
     clientSocket.Close();


 }

0 个答案:

没有答案