[英]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
)。 但MyClient
是TcpClient
,那么我需要做什么才能完成這樣的場景呢? 創建一個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.