|
Public Class UdpKeyListener
Private Const listenPort As Integer = 11053
Private m_exitCode As Integer = 0
Private m_messageCount As Integer = 0
Private m_handle As IntPtr = IntPtr.Zero
Private WithEvents m_BackgroundWorker As New System.ComponentModel.BackgroundWorker 'Asynchronous Non-Blocking Background Worker
Public Event OnMessageReceived(ByVal Sender As Object, ByVal msgCount As Integer, ByVal iRet As Integer, ByVal msg As String)
Private Sub m_BackgroundWorker_DoWork(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles m_BackgroundWorker.DoWork
Dim iRet As Integer = 1
Dim listener As New System.Net.Sockets.UdpClient(listenPort)
Dim groupEP As New System.Net.IPEndPoint(System.Net.IPAddress.Any, listenPort)
Try
Do Until ((iRet = 0) OrElse (iRet = -1))
Dim bytes As Byte() = listener.Receive(groupEP)
If bytes.Length > 6 AndAlso bytes(0) = 71 AndAlso bytes(1) = 77 AndAlso bytes(2) = 84 AndAlso bytes(3) = 77 AndAlso bytes(4) = 88 AndAlso bytes(5) = 88 Then 'GMTMXX
m_BackgroundWorker.ReportProgress(iRet, CStr(System.Text.Encoding.ASCII.GetString(bytes, 6, bytes.Length - 6)))
End If
Loop
Catch ex As Exception
Debug.Write(ex.ToString)
iRet = -1
Finally
listener.Close()
End Try
End Sub
Private Sub m_BackgroundWorker_ProgressChanged(ByVal sender As Object, ByVal e As System.ComponentModel.ProgressChangedEventArgs) Handles m_BackgroundWorker.ProgressChanged
If ((Not e.UserState Is Nothing) AndAlso (e.UserState.GetType Is GetType(String))) Then
m_messageCount += 1
Dim iRet As Integer = e.ProgressPercentage
Dim msg As String = CType(e.UserState, String)
If ((Not OnMessageReceivedEvent Is Nothing) AndAlso (OnMessageReceivedEvent.GetInvocationList.Length > 0)) Then
RaiseEvent OnMessageReceived(Me, m_messageCount, iRet, msg)
End If
End If
End Sub
Public Sub New()
m_BackgroundWorker.WorkerReportsProgress = True
m_BackgroundWorker.WorkerSupportsCancellation = True
m_BackgroundWorker.RunWorkerAsync()
End Sub
Public ReadOnly Property exitCode() As Integer
Get
Return m_exitCode
End Get
End Property
Public ReadOnly Property messageCount() As Integer
Get
Return m_messageCount
End Get
End Property
Public ReadOnly Property handle() As IntPtr
Get
Return m_handle
End Get
End Property
Public Shared Sub Send(ByVal msg As String)
Dim xClient As System.Net.Sockets.UdpClient = New System.Net.Sockets.UdpClient
Dim bytes As Byte() = System.Text.Encoding.ASCII.GetBytes("GMTMXX" & msg)
xClient.Send(bytes, bytes.Length, New System.Net.IPEndPoint(System.Net.IPAddress.Parse("255.255.255.255"), listenPort))
xClient.Close()
End Sub
End Class
|
By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.
If a file you wish to view isn't highlighted, and is a text file (not binary), please
let us know and we'll add colourisation support for it.
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.