当具有对NetworkStream的引用时,正在处理TcpClient

本文关键字:处理 TcpClient 引用 NetworkStream | 更新日期: 2023-09-27 18:19:49

假设我有以下代码:

public static Client Connect(string hostname, int port, bool useSsl)
{
    TcpClient tcpClient = new TcpClient(hostname, port);
    if (!useSsl)
    {
        return new Client(tcpClient.GetStream());
    }
    SslStream sslStream = new SslStream(tcpClient.GetStream());
    sslStream.AuthenticateAsClient(hostname);
    return new Client(sslStream);
}

当我编译这个时,代码分析告诉我,我应该在引用超出范围之前处理tcpClient。问题是我需要进一步使用底层流实例,并且我不能在这里处理tcpClient。同时,我不想为了稍后处理而在某个地方存储对tcpClient的引用,因为我只需要流。这里的正确解决方案是什么?谢谢

当具有对NetworkStream的引用时,正在处理TcpClient

public class Client : IDisposable
{
    private TcpClient tcpClient = null;
    public Client(string hostname, int port, bool useSsl) // c'tor
    {
        tcpClient = new TcpClient(hostname, port);
        if (!useSsl)
        {
            Init(tcpClient.GetStream());
            return;
        }
        SslStream sslStream = new SslStream(tcpClient.GetStream());
        sslStream.AuthenticateAsClient(hostname);
        Init(sslStream);            
    }
    private void Init(Stream stream)
    {
        // bla bla bla
    }
    public void Dispose()
    {  
        // this implementation of Dispose is potentially faulty (it is for illustrative purposes only)
        // http://msdn.microsoft.com/en-us/library/ms244737%28v=vs.80%29.aspx
        if( tcpClient != null ) {
            tcpClient.Close();
            tcpClient = null;
        }
    }
}

您可以通过两种方式来实现这一点。。1.通过ref或2.在顶部声明一个私有变量为SslStream SslStream=null;有这个

SslStream sslStream = new SslStream(tcpClient.GetStream()); 

将其或方法更改为如下所示。

public static SSLStream Connect(ref string hostname, ref int port, bool useSsl) 
{     
   TcpClient tcpClient = new TcpClient(hostname, port);
   if (!useSsl) 
   {
      return new Client(tcpClient.GetStream());
   }
   sslStream = new SslStream(tcpClient.GetStream()); // or the ref sslStream 
   sslStream.AuthenticateAsClient(hostname);
   tcpClient = null; or if implements IDisposable then do this
   if (tcpClient != null)
   {
      ((IDisposable)tcpClient).Dispose();
   }
   return sslStream; //if yo
}