Important alert: (current site time 5/27/2015 3:20:48 PM EDT)

VB icon

Easy to use multithreaded TCP/IP Client class

Submitted on: 5/15/2012 4:07:29 PM
By: Jeff Rondeau 
Level: Intermediate
User Rating: Unrated
Compatibility: VB.NET
Views: 4340
     Useful class for create TCP/IP connections on any given port. Included is the logic to break messages apart. This class is multi threaded and self contained.
Can't Copy and Paste this?
Click here for a copy-and-paste friendly version of this code!
Terms of Agreement:   
By using this code, you agree to the following terms...   
  1. You may use this code in your own programs (and may compile it into a program and distribute it in compiled format for languages that allow it) freely and with no charge.
  2. You MAY NOT redistribute this code (for example to a web site) without written permission from the original author. Failure to do so is a violation of copyright laws.   
  3. You may link to this code from another website, but ONLY if it is not wrapped in a frame. 
  4. You will abide by any additional copyright restrictions which the author may have placed in the code or code's description.
// Name: Easy to use multithreaded TCP/IP Client class
// Description:Useful class for create TCP/IP connections on any given port. Included is the logic to break messages apart. This class is multi threaded and self contained.
// By: Jeff Rondeau
//This code is copyrighted and has// limited warranties.Please see details.//**************************************

Imports System.Net
Imports System.Net.Sockets
Imports System.Threading
Imports System.Text.RegularExpressions
Public Class JSock
Private MySock As TcpClient
Private MyOutStream As NetworkStream
Private MyInStream As NetworkStream
Private InStreamThread As Thread
Private InStackThread As Thread
Private _HostIP As String
Private _HostPort As Long
Private m_MessageDelimiter As String = Chr(0)
Private MyMessageStack As MyMessageString
Public SocketConnected As Boolean
Public AutoReconnect As Boolean = True
Public Event ConnectionOpened()
Public Event ConnectionClosed()
Public Event ConnectionFailed(ByVal sReason As String)
Public Event IncomingMessage(ByVal sMessage As String)
Public Sub SendData(ByVal strdata As String)
Dim Mybytes() As Byte = System.Text.Encoding.ASCII.GetBytes(strdata & m_MessageDelimiter)
MyOutStream.BeginWrite(Mybytes, 0, Mybytes.Length, Nothing, Nothing)
Catch ex As Exception
End Try
End Sub
Public Sub Connect(ByVal HostIP As String, ByVal HostPort As Long, Optional ByVal Delimter As String = Chr(0))
m_MessageDelimiter = Delimter
_HostIP = HostIP
_HostPort = HostPort
InStreamThread = New Thread(AddressOf OpenSocketAndConnect)
InStreamThread.IsBackground = True
Catch ex As Exception
'RawCode.NewError(ex, System.Reflection.MethodBase.GetCurrentMethod.ToString, "Attempting to create connection thread" & _HostIP, False, "")
End Try
End Sub
#Region "Inline Socket Interface"
Private Sub OpenSocketAndConnect()
While AutoReconnect
MySock = New TcpClient
MySock.Connect(_HostIP, _HostPort)
MyOutStream = MySock.GetStream
MyInStream = MySock.GetStream
MyMessageStack = New MyMessageString
SocketConnected = True
InStackThread = New Thread(AddressOf ProcessMessageStack)
InStackThread.IsBackground = True
RaiseEvent ConnectionOpened()
Dim MyReadBuffer(4096) As Byte
Dim NumberOfBytesRead As Integer = 0
NumberOfBytesRead = MyInStream.Read(MyReadBuffer, 0, MyReadBuffer.Length)
If NumberOfBytesRead > 0 Then
MyMessageStack.MyMessage &= System.Text.Encoding.ASCII.GetString(MyReadBuffer, 0, NumberOfBytesRead)
RaiseEvent ConnectionClosed()
SocketConnected = False
Exit Do
End If
Catch ex As Exception
If Err.Number = 57 Then
RaiseEvent ConnectionClosed()
SocketConnected = False
RaiseEvent ConnectionFailed(Err.Description)
End If
SocketConnected = False
'RawCode.NewError(ex, System.Reflection.MethodBase.GetCurrentMethod.ToString, "Attempting to Connect To " & _HostIP, False, "")
End Try
Thread.Sleep(1000) 'wait 1 second between attempts 
End While
End Sub
''' <summary>
''' Monitors the Inbound Message Stack 
''' </summary>
''' <remarks>Raises IncomingMessage Event</remarks>
Private Sub ProcessMessageStack()
Dim bString As String = ""
Dim StringParts() As String
While AutoReconnect
' While MyInboundMessages.Count > 0
If Not String.IsNullOrEmpty(MyMessageStack.MyMessage) Then
' <> String.Empty Then
bString &= MyMessageStack.MyMessage
MyMessageStack.MyMessage = ""
End If
If bString <> "" Then
StringParts = Regex.Split(bString, "(?<=" & m_MessageDelimiter & ")")
bString = String.Empty
For i = LBound(StringParts) To UBound(StringParts)
If StringParts(i).Contains(m_MessageDelimiter) Then
StringParts(i).Replace(m_MessageDelimiter, String.Empty)
RaiseEvent IncomingMessage(StringParts(i))
bString &= StringParts(i)
End If
End If
Catch ex As Exception
'RawCode.NewError(ex, System.Reflection.MethodBase.GetCurrentMethod.ToString, "Attempting to Receive Data To " & _HostIP, False, bString)
End Try
'End While
End While
End Sub
#End Region
Private Class MyMessageString
Public MyMessage As String = ""
End Class
End Class

Other 3 submission(s) by this author


Report Bad Submission
Use this form to tell us if this entry should be deleted (i.e contains no code, is a virus, etc.).
This submission should be removed because:

Your Vote

What do you think of this code (in the Intermediate category)?
(The code with your highest vote will win this month's coding contest!)
Excellent  Good  Average  Below Average  Poor (See voting log ...)

Other User Comments

 There are no comments on this submission.

Add Your Feedback
Your feedback will be posted below and an email sent to the author. Please remember that the author was kind enough to share this with you, so any criticisms must be stated politely, or they will be deleted. (For feedback not related to this particular code, please click here instead.)

To post feedback, first please login.