Public Class ConnectionPDA
Private quitFlag As Boolean
Private conOut As System.Net.Sockets.TcpClient
Private netStream As System.Net.Sockets.NetworkStream
Private linOpt As System.Net.Sockets.LingerOption
Private myTimer As System.Windows.Forms.Timer
Private bTimedOut As Boolean
#Region "Constructors and Destructors"
Public Sub New()
'Create the timer
myTimer = New System.Windows.Forms.Timer
'Need to tell it where to send time tick messages.
AddHandler myTimer.Tick, AddressOf TimerEventProcessor
'This is set so that we can know the status if nothing is received.
bTimedOut = False
' Sets the timer interval to 5 seconds.
myTimer.Interval = 5000
myTimer.Enabled = False
quitFlag = True
linOpt = New System.Net.Sockets.LingerOption(True, 5)
End Sub
Public Sub Dispose()
'This may not be essential, but give it a go.
If Not netStream Is Nothing Then
netStream.Close()
End If
If Not conOut Is Nothing Then
conOut.Close()
End If
myTimer.Dispose()
End Sub
#End Region
#Region "Public Functions"
'If this is true, then the time event fired. Basically, this means that if
'RetrieveData() returned an empty string, it was because of timing out.
Public Function TimedOut() As Boolean
TimedOut = Me.TimedOut
End Function
Public Function BeginCommunicate() As Boolean
Dim st1 As String
Dim flag As Boolean
Dim rVal As Integer
Try
conOut = New System.Net.Sockets.TcpClient("PPP_PEER", 2000)
conOut.LingerState = linOpt
netStream = conOut.GetStream
BeginCommunicate = True
Catch ex As Exception
BeginCommunicate = False
End Try
End Function
Public Function RetrieveData() As String
Dim recBuff(2048) As Byte
Dim recCount As Integer
Dim st1 As String
Dim hasRead As Boolean
hasRead = False
'Get ready to read.
quitFlag = True
myTimer.Enabled = True
Try
Do While quitFlag
If netStream.DataAvailable Then
recCount = netStream.Read(recBuff, 0, 2048)
End If
If recCount > 0 Then
hasRead = True
'Turn it into a string.
st1 &= System.Text.Encoding.Default.GetString(recBuff, 0, recCount)
'Clear out the buffer.
recBuff.Clear(recBuff, 0, 2048)
recCount = 0
Else
'If hasRead is set, then something has been received, but the last loop
'returned nothing. Therefore, we are done reading.
If hasRead Then
'This is simply cleared to stop the loop.
quitFlag = False
End If
'DoEvents, but only if nothing is coming in!
Application.DoEvents()
End If
Loop
Catch ex As Exception
'Nothing can be done here, but that's ok.
MsgBox(ex.Message)
End Try
'Get out.
Me.bTimedOut = False
RetrieveData = st1
End Function
Public Function SendData(ByVal st1 As String) As Boolean
Dim sendBuff(2048) As Byte
Try
sendBuff = System.Text.Encoding.Default.GetBytes(st1.ToCharArray())
netStream.Write(sendBuff, 0, sendBuff.GetLength(0))
SendData = True
Catch ex As Exception
SendData = False
End Try
End Function
#End Region
#Region "Private Functions"
Private Sub TimerEventProcessor(ByVal myObject As Object, ByVal myEventArgs As EventArgs)
myTimer.Enabled = False
quitFlag = False
Me.bTimedOut = True
End Sub
#End Region
End Class