Search code examples
vb.netsocketsnetwork-programmingtcpclienttcplistener

connect to a tcpListener with a extended class of tcpClient


I’ve created a new class inherited TcpClient class that has a property named (for example) ClientName . here is this class’s definition :

Public Class MyTcpClient
    Inherits Net.Sockets.TcpClient

    Private _ClintName As String

    Sub New(ByVal host As String, ByVal port As Integer, ByVal ClientName As String)
        MyBase.New()
        _ClintName = ClientName
    End Sub

    Public Property ClientName()
        Get
            Return _ClintName
        End Get
        Set(ByVal value)
            _ClintName = value
        End Set
    End Property
End Class

I created an instant of this class and tried to connect this client to a server (TcpListener) with below code :

Try
    client = New MyTcpClient(ip, port , "ClientName")
Catch ex As Exception
    xUpdate("Can't connect to the server!")
End Try 

But every time I try to connect to the server an error occur with this massage : “System.InvalidOperationException: The operation is not allowed on non-connected sockets.” Now , if I change MyTcpClient to Net.Socket.TcpClient every thing will be ok.

Try
    client = New Net.Socket.TcpClient(ip, port)
Catch ex As Exception
    xUpdate("Can't connect to the server!")
End Try

Is there any way to connect to a TcpListener with an extended class of TcpClient like my class?


Solution

  • thanks jmcilhinney ....

    i tested your code , so now my first error is removed , but on the server side a new error occur . the error message is : "Unable to cast object of type 'System.Net.Sockets.TcpClient' to type 'ServerChat.MyTcpClient'."

    the code in server side is :

    Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs) Handles MyBase.Load
        Dim NewClient As MyTcpClient
        Listning = New TcpListener(GetMyIP, 3818)
        Listning.Start()
        UpdateList("Server Starting", False)
        Listning.BeginAcceptTcpClient(New AsyncCallback(AddressOf AcceptClient), Listning)
    End Sub
    
    Sub AcceptClient(ByVal ar As IAsyncResult)
        NewClient = Listning.EndAcceptTcpClient(ar)
        UpdateList("New Client Joined!", True)
        Listning.BeginAcceptTcpClient(New AsyncCallback(AddressOf AcceptClient), Listning)
    End Sub
    

    the error occue in AcceptClient sub on first line :

    NewClient = Listning.EndAcceptTcpClient(ar)
    

    should i do any change on tcpListener object or something like that? or my attempt basically is wrong?