r/visualbasic • • Dec 22 '20

Simple UDP Receiver

Hi everyone, I am super noob, i have been using several languages only for solving various problems from art and design point of view, so no real programmer but fairly it knowledgeable.
I am now in need to create a simple tool capable of opening a UDP Socket to listen for messages sent from a machinery that sends something like this:

DATE;21/12/2020
TIME;15:13:43
MODE;NORMAL
UNIT;1
SEQ;6;0
SID;00005
PID;
ID;BORIS
TEST;LMG
OPERATOR;

I have started building something, but I've got stuck as this point

Imports System.Text
Imports System.Net
Imports System.Net.Sockets
Imports System.Reflection

Class MainWindow
    Private Sub MainWindow_Loaded(sender As Object, e As RoutedEventArgs) Handles Me.Loaded
        Log.AppendText("Starting" + Environment.NewLine())
    End Sub

    Private Sub Button_Click(sender As Object, e As RoutedEventArgs)

        Dim UDPClient As UdpClient = New UdpClient()
        UDPClient.Client.ReceiveTimeout = 100
        UDPClient.Client.Blocking = False

        UDPClient.Client.SetSocketOption(SocketOptionLevel.Socket,
         SocketOptionName.ReuseAddress, True)
        UDPClient.Client.Bind(New IPEndPoint(IPAddress.Any, 1200))

        Try
            Log.AppendText("Opening Connection" + Environment.NewLine())
            Dim iepRemoteEndPoint As IPEndPoint = New IPEndPoint(IPAddress.Any, 0)
            Dim strMessage As String = String.Empty
            Do
                Log.AppendText("Loop" + Environment.NewLine())

                Dim bytRecieved As Byte() = UDPClient.Receive(iepRemoteEndPoint)
                strMessage = Encoding.ASCII.GetString(bytRecieved)

                Log.AppendText(strMessage + Environment.NewLine())

            Loop While (strMessage <> "END_RESULTS")
            UDPClient.Close()
        Catch ex As Exception
            Log.AppendText(ex.ToString() + Environment.NewLine())
        End Try
    End Sub

End Class

The interface so far (in the future i hope to implement TCP)

Any help is greatly appreciated... Thanks

P.S.
I use netcat to test the tool and send udp messages

5 Upvotes

5 comments sorted by

4

u/Bittenfleax Dec 22 '20

I've done a UDP listener service before - this answer helped me complete it vb.net - Visual Basic UDPClient Server/Client model? - Stack Overflow

2

u/ZaldorNariash Dec 22 '20

Thanks that helped a lot, Now I receive the message but i cannot put on textbox because it is "owned" by another thread, any help with that? Thanks

Imports System.Text

Imports System.Net

Imports System.Net.Sockets

Imports System.Reflection

Imports System.Threading

Class MainWindow

'''''''''''''''''''''''Set up variables''''''''''''''''''''

Private Const port As Integer = 1200 'Port number to send/recieve data on

Private receivingClient As UdpClient 'Client for handling incoming data

Private receivingThread As Thread 'Create a separate thread to listen for incoming data, helps to prevent the form from freezing up

Private closeThat As Boolean = False 'Used to close clients if form is closing

'''''''''''''''''''''Setup receiving client'''''''''''''

Private Sub InitializeReceiver()

receivingClient = New UdpClient(port)

Dim start As ThreadStart = New ThreadStart(AddressOf Receiver)

receivingThread = New Thread(start)

receivingThread.IsBackground = True

receivingThread.Start()

End Sub

'''''''''''''''''''''Start receiving loop'''''''''''''''''''''''

Private Sub Receiver()

Dim endPoint As IPEndPoint = New IPEndPoint(IPAddress.Any, port) 'Listen for incoming data from any IP address on the specified port (I personally select 9653)

While (True) 'Setup an infinite loop

Dim data() As Byte 'Buffer for storing incoming bytes

data = receivingClient.Receive(endPoint) 'Receive incoming bytes

Dim message As String = Encoding.ASCII.GetString(data) 'Convert bytes back to string

Log.AppendText(message & Environment.NewLine)

If closeThat = True Then 'Exit sub if form is closing

Exit Sub

End If

End While

End Sub

''''''''''''''''''''Initialize listening & sending subs'''''''''''''''''

Private Sub MainWindow_Loaded(sender As Object, e As RoutedEventArgs) Handles Me.Loaded

InitializeReceiver() 'Starts listening for incoming data

End Sub

Private Sub MainWindow_Closed(sender As Object, e As EventArgs) Handles Me.Closed

closeThat = True 'Tells receiving loop to close

receivingClient.Close()

End Sub

Private Sub Button_Click(sender As Object, e As RoutedEventArgs)

If closeThat = True Then

closeThat = False

Else

closeThat = True

End If

End Sub

End Class

4

u/Bittenfleax Dec 22 '20

Take a look at this: https://docs.microsoft.com/en-us/dotnet/desktop/winforms/controls/how-to-make-thread-safe-calls-to-windows-forms-controls?view=netframeworkdesktop-4.8

Read the beginning to get an understanding then take a look under the "Example: Use the Invoke method with a delegate" header and it should lead you to your solution :)

1

u/ZaldorNariash Dec 23 '20

Thank you, I always wanted to use multi-thread, but I believe the solution pointed works with Win Forms and not WPF, I think I read something about "dispatcher" can you confirm?
Thanks again

1

u/Bittenfleax Dec 23 '20

Ah I've never done a WPF form before - I tend to stick to WinForm for small simple applications as it's good for rapid prototyping