I am writing server application and I want to do something like this:
class MyClient : TcpClient
{
public StreamReader Reader { get; }
public StreamWriter Writer { get; }
public MyClient()
{
Reader = new StreamReader(this.GetStream());
Writer = new StreamWriter(this.GetStream());
}
}
Then I want to listen to an incoming connection and create MyClient object:
TcpListener listener= new TcpListener(IPAddress.Parse(Constants.IpAddress), Constants.Port);
MyClient client = (MyClient)listener.AcceptTcpClient();
I know that I cant downcast like this (TcpClient is not MyClient).
But MyClient Is TcpClient, so what do I need to do, to accomplish such scenario?
create a MyClient constructor that takes TcpClient argument and invokes base TcpClient class constructor. I want MyClient to be a TcpClient instead of having TcpClient property. Or maybe Socket class will be better in my case?
Doing
(MyClient)listener.AcceptTcpClient();
will never work, whatever you do, because it always return regular TcpClient (and this method is not virtual in TcpListener so you cannot change that). Same story with AcceptSocket. You can create a proxy class which will not inherit from TcpClient but will implement all the same public members and proxy their implementation to real TcpClient you store in private field and pass to constructor. However then you cannot pass that class to any method that expects regular TcpClient.
Implementation of AcceptTcpClient creates TcpClient using constructor which accepts socket, however this constructor is internal so you cannot use this way.
Another option that comes to mind is:
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());
}
}
And then pass socket from AcceptSocket to constructor. But I don't like it, because default constructor of TcpClient will be called, which creates new socket (which is disposed at the first line of constructor above).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With