Home > Code Dump > Event-Driven TCP Client in VB.NET

Event-Driven TCP Client in VB.NET

A handy little class I adjusted and used
By 30/12/10 [Last Edited by Joseph 30/12/10]
BOOKMARK
LOGIN
REGISTER
This class has two events, exErr(errorDescription As String) and dataReceived(stringData As String). This class is designed only for sending and receiving string data; data sent is appended with a carriage return and line feed.

Public Class hhNetwork
    Private objClient As System.Net.Sockets.TcpClient
    Private Const BYTES_TO_READ As Integer = 255
    Private byReadBuffer(BYTES_TO_READ) As Byte
    Private bConnected As Boolean
    Public Event dataReceived(ByVal szData As String)
    Public Event exErr(ByVal szErr As String)

    Public Function isConnected()
        Return bConnected
    End Function

    Public Function connect(ByVal szIP As String) As Boolean
        bConnected = True
        Try
            objClient = New System.Net.Sockets.TcpClient(szIP, 23)
            objClient.GetStream.BeginRead(byReadBuffer, 0, BYTES_TO_READ, AddressOf Me.doRead, Nothing)
        Catch ex As Exception
            RaiseEvent exErr(ex.ToString)
            bConnected = False
        End Try
        Return bConnected
    End Function

    Private Sub doRead(ByVal ar As System.IAsyncResult)
        Dim nTotalRead As Integer
        Try
            nTotalRead = objClient.GetStream.EndRead(ar) 'Ends the reading and returns the number of bytes read.
        Catch ex As Exception
            RaiseEvent exErr(ex.ToString)
        End Try

        If nTotalRead > 0 Then
            Dim szReceivedString As String = System.Text.Encoding.UTF8.GetString(byReadBuffer, 0, nTotalRead)
            RaiseEvent dataReceived(szReceivedString)
        End If

        Try
            objClient.GetStream.BeginRead(byReadBuffer, 0, BYTES_TO_READ, AddressOf doRead, Nothing) 'Begin the reading again.
        Catch ex As Exception
            RaiseEvent exErr(ex.ToString)
        End Try
    End Sub

    Public Sub sendMessage(ByVal SzMsg As String)
        Dim objSw As IO.StreamWriter
        Try
            objSw = New IO.StreamWriter(objClient.GetStream)
            objSw.Write(SzMsg & vbCrLf)
            objSw.Flush()
        Catch ex As Exception
            RaiseEvent exErr(ex.ToString)
        End Try
    End Sub

End Class