Specified cast is not valid TcpClient TcpListener

Specified cast is not valid TcpClient TcpListener

Post by Nuno Magal » Sun, 09 Oct 2005 05:32:03


This code gives me the runtime error "Specified cast is not valid":
MyTcpClient ClientTcp=(MyTcpClient)ListenerTcp.AcceptTcpClient();

MyTcpClient is a class that inherits from TcpClient. Why can't I do
this? Is it possible to get the remote endpoint without have to go to
the underlying socket? I don't want to mess with sockets and I just
want the network stream to read/write data.
 
 
 

Specified cast is not valid TcpClient TcpListener

Post by QnJlbmRhbi » Sun, 09 Oct 2005 05:54:05

Your problem is one of basic inheritance... a dog is a mammal, but not all
mammals are dogs.

You are trying to typecast a base class into a class that inherits the base
class... this is not possible. It like typecasting a mammal to be a dog...
in some cases it might work, if the object you are receiving is actually of
that type (which it is not in this case).

As for accessing the end point of the socket... the quickest way to it is
through the socket you receive... namely through it Remo *** dPoint
property... to do so you would simply say:

EndPoint ep = ListenerTcp.AcceptTcpClient().Remo *** dPoint;

As for creating a network stream... again you would need the socket in some
way... the optimal way to do it would be to capture the returned class from
AcceptTcpClient() and pass it into the constructor of NetworkStream.

Brendan