Specified cast is not valid TcpClient TcpListener

N

Nuno Magalhaes

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.
 
G

Guest

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’s 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’s RemoteEndPoint
property... to do so you would simply say:

EndPoint ep = ListenerTcp.AcceptTcpClient().RemoteEndPoint;

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top