thatscrap12543 0 Newbie Poster

Hi, networking is new to me in vb.net as I normally use third party components to do my networking like Winsock Orcas. However I want to make my own classes for networking. The following is what I have so far. It has problems.

1) Its disorganized...particularly the way I'm multi-threading, but this is a learning experience rather than a final product.

2) I need a way to reset the connection on a disconnect. I get a funky error message that tells me I have to call beginconnect on a separate thread, i have to have a different endpoint yada yada. I have a good feeling I'm going to have to rewrite the whole thing to cure this, but I was planning on rewriting it anyways.

3)I think my method of disposing my class is wrong.

Other than all this, the class works well as far as I'm concerned.

Imports System.Net
Imports System.Net.Sockets
Imports System.IO
Imports System.Threading
Namespace LowLevelNetwork



    Public Class ClientTCPConnection_Strings
        Implements IDisposable
        '====================================================================================================================================================
        Dim Stream As NetworkStream
        Dim Writer As BinaryWriter
        Dim Reader As BinaryReader
        Dim Client As New TcpClient()
        Dim encryp_str As String 'encryption
        Dim ipaddress_str As String = "" 'ip address
        Dim portnumber_int As Integer = 0 'port number
        Dim alwaystry_bool As Boolean = False
        Dim ReceiveThread As New Thread(AddressOf ReceiveData)

        '====================================================================================================================================================
        Public Event DataReceived(ByVal sender As Object, ByVal data As String)
        Public Event OnConnection(ByVal sender As Object)
        Public Event OnConnectionFailed(ByVal sender As Object, ByVal errMessage As String)
        Public Event OnDisconnect(ByVal sender As Object)
        Public Event OnDecryptionBreach(ByVal sender As Object)
        '====================================================================================================================================================
        ''' <summary>
        ''' Creates a new client to host connection that is soley based on strings. Not for file or memory transfer. If encryptionkey is provided, the connection will be encrypted.
        ''' </summary>
        ''' <remarks></remarks>
        Sub New(Optional ByVal EncryptionKey As String = "")
            encryp_str = EncryptionKey
        End Sub
        ''' <summary>
        ''' Destroys the connection properly.
        ''' </summary>
        ''' <remarks></remarks>
        Public Overloads Sub Dispose() Implements IDisposable.Dispose
            Dispose(True)
            GC.SuppressFinalize(Me)
        End Sub

        Protected Overridable Overloads Sub Dispose(ByVal disposing As Boolean)
            If disposing Then
                Try
                    ReceiveThread.Abort()
                Catch ex As Exception
                End Try
                Stream.Dispose()
                Writer.Dispose()
                Reader.Dispose()

                ' Free other state (managed objects).
            End If
            ' Free your own state (unmanaged objects).
            ' Set large fields to null.
        End Sub

        Protected Overrides Sub Finalize()
            ' Simply call Dispose(False).
            Dispose(False)
        End Sub
        ''' <summary>
        ''' Signifies whether or not this client should keep trying to connect, after a failure to connect. DEFAULT: = False
        ''' </summary>
        ''' <remarks></remarks>
        Public Property AlwaysTryConnect() As Boolean

            Get
                Return alwaystry_bool
            End Get

            Set(ByVal Value As Boolean)
                alwaystry_bool = Value
            End Set

        End Property
        ''' <summary>
        ''' Gets or sets ipaddress of host
        ''' </summary>
        ''' <remarks></remarks>
        Public Property Ip_Address() As String

            Get
                Return ipaddress_str
            End Get

            Set(ByVal Value As String)
                ipaddress_str = Value
            End Set

        End Property

        ''' <summary>
        ''' Gets or sets port number of host
        ''' </summary>
        ''' <remarks></remarks>
        Public Property PortNumber() As Integer

            Get
                Return portnumber_int
            End Get

            Set(ByVal Value As Integer)
                portnumber_int = Value
            End Set

        End Property
        ''' <summary>
        ''' Gets if the client is connected.
        ''' </summary>
        ''' <remarks></remarks>
        Public ReadOnly Property IsConnected() As Boolean
            Get
                Return Client.Connected
            End Get
        End Property
        '====================================================================================================================================================
        '====================================================================================================================================================
        '====================FUNCTIONS=======================================================================================================================
        '====================================================================================================================================================
        '====================================================================================================================================================
        ''' <summary>
        ''' Attempts a connection to host with port number
        ''' </summary>
        ''' <remarks></remarks>
        Function Connect()
            Try
                Dim ConThread As New Thread(AddressOf AttemptConnect)
                ConThread.IsBackground = True
                ConThread.Start()
            Catch Err As Exception
                RaiseEvent OnConnectionFailed(Me, "Error connecting to host, ERROR CODE: 1" & vbNewLine & "Details: " & vbNewLine & Err.Message)
                Return 1
            End Try
            Return 0
        End Function
        ''' <summary>
        ''' Sends data and returns when data has been received. When received, the OnDataReceived event will not fire.
        ''' </summary>
        ''' <remarks></remarks>
        Function SendandWait(ByVal data As String) As String
            If Client.Connected = False Then
                Disconnect()
                Return 0
                Exit Function
            End If
            Writer.Write(data)
            Do
                If Stream.DataAvailable Then
                    Return Decrypt(Reader.ReadString())
                End If
            Loop
        End Function
        ''' <summary>
        ''' Sends data.
        ''' </summary>
        ''' <remarks></remarks>
        Sub Send(ByVal data As String)
            Try
                Writer.Write(Encrypt(data))
            Catch ex As Exception
                Disconnect()
            End Try
        End Sub

        'thread subs
        Private Sub AttemptConnect()
            Try
                Client.Connect(IPAddress.Parse(ipaddress_str), portnumber_int)
                Stream = Client.GetStream() 'set stream to correspond with new stream
                Writer = New BinaryWriter(Stream)
                Reader = New BinaryReader(Stream)
                ReceiveThread.IsBackground = True
                ReceiveThread.Start()

                RaiseEvent OnConnection(Me) 'raise that we connected successfully
            Catch Err As Exception
                RaiseEvent OnConnectionFailed(Me, "Error connecting to host, ERROR CODE: 2" & vbNewLine & "Details: " & vbNewLine & Err.Message)
                If alwaystry_bool Then
                    Thread.Sleep(TimeSpan.FromSeconds(1))
                    AttemptConnect()
                End If
            End Try
        End Sub
        Private Sub ReceiveData() 'thread sub for connect
            Do
                Thread.Sleep(1)
                If Stream.DataAvailable Then
                    Dim data As String = Reader.ReadString()
                    RaiseEvent DataReceived(Me, Decrypt(Reader.ReadString()))
                End If
            Loop
        End Sub

        Private Sub Disconnect()

            Writer = Nothing
            Reader = nothing
            RaiseEvent OnDisconnect(Me)
        End Sub

        'MISC

        Private Function Decrypt(ByRef s As String)
            On Error GoTo ERR
            If encryp_str = "" Then
                Return s
            Else
                Return networksecurity.Decrypt(s, encryp_str)
            End If
            Exit Function
ERR:
            RaiseEvent OnDecryptionBreach(Me)
        End Function
        Private Function Encrypt(ByRef s As String)
            If encryp_str = "" Then
                Return s
            Else
                Return networksecurity.Encrypt(s, encryp_str)
            End If
        End Function



        Private Sub ThrowError(ByVal errortxt As String)
            Throw New Exception(errortxt)
        End Sub

    End Class



    '
    '
    '



End Namespace
Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.20 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.