Important alert: (current site time 7/23/2014 11:14:21 AM EDT)
 

VB icon

Easy to use multithreaded TCP/IP Client class

Email
Submitted on: 5/15/2012 4:07:29 PM
By: Jeff Rondeau 
Level: Intermediate
User Rating: Unrated
Compatibility: VB.NET
Views: 3559
 
     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.
 
code:
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 http://www.Planet-Source-Code.com/vb/scripts/ShowCode.asp?txtCodeId=8776&lngWId=10//for 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)
Try
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))
Try
m_MessageDelimiter = Delimter
_HostIP = HostIP
_HostPort = HostPort
'InStreamThread.Abort()
InStreamThread = New Thread(AddressOf OpenSocketAndConnect)
InStreamThread.IsBackground = True
InStreamThread.Start()
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
Try
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
InStackThread.Start()
RaiseEvent ConnectionOpened()
Dim MyReadBuffer(4096) As Byte
Dim NumberOfBytesRead As Integer = 0
Do
NumberOfBytesRead = MyInStream.Read(MyReadBuffer, 0, MyReadBuffer.Length)
If NumberOfBytesRead > 0 Then
Monitor.Enter(MyMessageStack)
MyMessageStack.MyMessage &= System.Text.Encoding.ASCII.GetString(MyReadBuffer, 0, NumberOfBytesRead)
Monitor.Exit(MyMessageStack)
Else
RaiseEvent ConnectionClosed()
InStackThread.Abort()
SocketConnected = False
Exit Do
End If
Loop
Catch ex As Exception
If Err.Number = 57 Then
RaiseEvent ConnectionClosed()
InStackThread.Abort()
SocketConnected = False
Else
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
Try
Monitor.Enter(MyMessageStack)
If Not String.IsNullOrEmpty(MyMessageStack.MyMessage) Then
' <> String.Empty Then
bString &= MyMessageStack.MyMessage
MyMessageStack.MyMessage = ""
End If
Monitor.Exit(MyMessageStack)
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))
Else
bString &= StringParts(i)
End If
Next
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
Thread.Sleep(10)
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.