Specified cast is invalid error using my own class?

  • Thread starter Thread starter James
  • Start date Start date
J

James

I'm a newbie to vb.net, and classes were something I never played with in
"standard" vb, but...

Basically,part of my program comprises of some tcp/ip stuff, and I used the
following code to start off the connection:

Public Sub Main()
Const PortNumber As Integer = 8022
Dim tcpListener As New TcpListener(PortNumber)
tcpListener.Start()
Try
'Wait for a connection.
Dim theClient As SubTCPClient = tcpListener.AcceptTcpClient()
Dim networkStream As NetworkStream = theClient.GetStream()

Now, the "subtcpclient" used to be just tcpclient (i.e. the built-in base
class) and all worked well. I needed access to some of the "protected"
properties and methods though, so after some googling I found a needed to
create my own sub class. This is done as:

Public Class SubTCPClient
Inherits TcpClient
Public Sub New()
End Sub
Public Function IsConnActive() As Boolean
IsConnActive = Me.Active
End Function
End Class

But since I did this it no longer works. There aren't any errors in the dev
environment, and the program runs, but as soon as a client connection is
received (the "dim client as subtcpclient... blah line), I get the
"specified cast is invalid" error.
It looks like this is to do with type conversion, but I can't see where I am
doing that, and my new class is based on the same one as it used to work
with, so I don't think thats it...

Any ideas?
James
 
Your supplied will run without error (despite the warning about your
obsolete usage of the New TcpListener call), just hanging on the
AcceptTcpClient line waiting for the client. So the actual error
obviously has something to do with when/how the connection is made. In
short, you haven't given enough detail for anyone to help ya decipher
the problem here.
 
James wrote:


tcpListener.AcceptTcpClient returns a TCPClient object not a
SubTCPClient object. Even though your SubTCPClient class inherits from
TCPClient.

Firstly, do you have Option Strict On at the top of your code?

Secondly, what happens if you cast the return value from the
AcceptTcpClient method like this: (I divided the lines so my reply
would fit better):

Dim theClient As SubTCPClient

theClient = DirectCast(tcpListener.AcceptTcpClient(),SubTCPClient)

Chris
 
Back
Top