1

我有一个简单的类来处理客户端和服务器之间的连接。内存管理和异常处理

要让多个用户同时与服务器通信,每个新的客户端连接都在单独的线程上进行。

在这个类中,我创建了两个流,作为客户端的入站和出站流。我首先创建了这些字段,然后在一个单独的方法中初始化该对象,只是因为该对象在其他几个地方使用。

我已经到了要重构代码的地步,以使它更健壮,我的第一个端口是内存管理。我已经开始喜欢using()语句,但注意到由于代码的结构方式,我无法真正找到实现它的方法。 这意味着我有一个相当恼人的方法,只是用于关闭底层连接,没有更多。另外,我开始实现异常处理,并且很好奇是否用一个try {}语句将方法中的整个代码包装在一个方法中,然后将顺序catch()块与适用的异常类型相联系是最好的办法。

我希望我能正确解释自己,我会发布一个片段供您查看。

谢谢!

//Fields 
     TcpClient tcpClient; 

     //The thread that will send information to the client 
     private Thread thrSender; 
     private StreamReader srReceiver; 
     private StreamWriter swSender; 
     private string currentUser; 
     private string strResponse; 

     //The constructor of the class takes in a TCP connection 
     public Connection(TcpClient tcpCon) 
     { 
      tcpClient = tcpCon; 

      //The thread that accepts the client and waits messages 
      thrSender = new Thread(AcceptClient); 

      //The thread calls the AcceptClient method 
      thrSender.Start(); 
     } 

     private void CloseConnection() 
     { 
      //Close the currently open objects 
      tcpClient.Close(); 
      srReceiver.Close(); 
      swSender.Close(); 
     } 

     //Occurs when a new client is accepted 
     private void AcceptClient() 
     { 
      srReceiver = new StreamReader(tcpClient.GetStream()); 
      swSender = new StreamWriter(tcpClient.GetStream()); 

      //Read account information from the client 
      currentUser = srReceiver.ReadLine(); 

      //Examine response from client 
      if (currentUser != "") 
      { 
       //Store the user name in the hash table 
       if (ChatServer.htUsers.Contains(currentUser) == true) 
       { 
        //0 means not connected - Writes error to Client and Server log 
        swSender.WriteLine("0|This username already exists."); 
        swSender.Flush(); 
        CloseConnection(); 
        return; 
       } 
       //More if/else if/else statements 
       //... 

     } 

    } 

回答

1

你可以因为其他地方没有提及这样的事情很容易的AcceptClient方法中,使它们局部变量处理两个流:

private void AcceptClient() 
{ 
    using (StreamReader srReceiver = new StreamReader(tcpClient.GetStream())) 
    { 
     using (StreamWriter swSender = new StreamWriter(tcpClient.GetStream())) 
     { 
      // ... 
     } 
    } 
} 

的TcpClient的是因为它更靠谱正在一个线程上创建并在另一个线程上清理。除非你可以改变,否则最好的选择将是在try/finally中实现清理。

private void AcceptClient() 
{ 
    try 
    { 
     using (StreamReader srReceiver = new StreamReader(tcpClient.GetStream())) 
     { 
      using (StreamWriter swSender = new StreamWriter(tcpClient.GetStream())) 
      { 
       // ... 
      } 
     } 
    } 
    finally 
    { 
     tcpClient.Dispose(); 
    } 
} 

finally子句将调用try子句是否抛出异常。

+0

非常好,谢谢! – 2010-10-23 19:17:33

+0

不客气! – Steve 2010-10-24 09:33:23