簡體   English   中英

在C#中擴展TcpClient類

[英]Extending TcpClient class in C#

我正在編寫服務器應用程序,我想做這樣的事情:

class MyClient : TcpClient
{        
    public StreamReader Reader { get; }
    public StreamWriter Writer { get; }
    public MyClient()
    {
          Reader = new StreamReader(this.GetStream());
          Writer = new StreamWriter(this.GetStream());           
    }       
}

然后我想聽一個傳入的連接並創建MyClient對象:

TcpListener listener= new TcpListener(IPAddress.Parse(Constants.IpAddress), Constants.Port);
MyClient client = (MyClient)listener.AcceptTcpClient();

我知道我不能像這樣垂頭喪氣( TcpClient不是MyClient )。 MyClientTcpClient ,那么我需要做什么才能完成這樣的場景呢? 創建一個MyClient構造函數,該構造函數接受TcpClient參數並調用基本TcpClient類構造函數。 我希望MyClient成為TcpClient而不是TcpClient屬性。 或者也許Socket類在我的情況下會更好?

(MyClient)listener.AcceptTcpClient();

無論你做什么都不會工作,因為它總是返回常規TcpClient (這個方法在TcpListener不是虛擬的,所以你不能改變它)。 AcceptSocket相同的故事。 您可以創建一個代理類,該代理類不會從TcpClient繼承,但會實現所有相同的公共成員,並將其實現代理到您存儲在私有字段中的實際TcpClient並傳遞給構造函數。 但是,您無法將該類傳遞給任何需要常規TcpClient

AcceptTcpClient TcpClient使用接受套接字的構造函數創建TcpClient ,但是這個構造函數是內部的,因此您不能使用這種方式。

想到的另一個選擇是:

class MyClient : TcpClient
{
    public StreamReader Reader { get; }
    public StreamWriter Writer { get; }
    public MyClient(Socket acceptedSocket)
    {
        this.Client.Dispose();
        this.Client = acceptedSocket;
        this.Active = true;
        Reader = new StreamReader(this.GetStream());
        Writer = new StreamWriter(this.GetStream());
    }
}

然后將套接字從AcceptSocket傳遞給構造函數。 但我不喜歡它,因為將調用TcpClient默認構造函數, TcpClient會創建新的套接字(它位於上面構造函數的第一行)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM