Visual Basic UDPClient Server/Client model?

Postman picture Postman · Apr 23, 2013 · Viewed 16.1k times · Source

So I'm trying to make a very simple system to send messages from a client to a server (and later on from server to client as well, but baby steps first). I'm not sure exactly how to use UDPClient to send and receive messages (especially to receive them), mostly because I don't have anything triggering the ReceiveMessage() function and I'm not sure what would.

Source Code is at this link, go to File>Download. It is already built if you want to just run the exe.

So my question is basically: How can I easily use UDPClient, how can I get this system to work and what are some tips for executing this kind of connection? Anything I should watch out for (threading, issues with code,etc)?

Source.

Answer

Sam picture Sam · Apr 26, 2013

You need first need to set up two UdpClients. One client for listening and the other for sending data. (You'll also need to pick a free/unused port number and know the IP address of your target - the machine you want to send data to.)

To set up the receiver,

  1. Instantiate your UdpClient variable with the port number you chose earlier,

  2. Create a new thread to avoid blocking while receiving data,

  3. Loop over the client's receive method for as long as you want to receive data (the loop's execution should be within the new thread),

  4. When you receive one lot of data (called a "packet") you may need to convert the byte array to something more meaningful,

  5. Create a way to exit the loop when you want to finish receiving data.

To set up the sender,

  1. Instantiate your UdpClient variable with the port number you chose earlier (you may want to enable the ability to send broadcast packets. This allows you to send data to all listeners on your LAN),

  2. When you need to transmit data, convert the data to a byte array and then call Send().

I'd suggest that you have a quick skim read through this.

Here's some code to get you started off...

'''''''''''''''''''''''Set up variables''''''''''''''''''''
Private Const port As Integer = 9653                         'Port number to send/recieve data on
Private Const broadcastAddress As String = "255.255.255.255" 'Sends data to all LOCAL listening clients, to send data over WAN you'll need to enter a public (external) IP address of the other client
Private receivingClient As UdpClient                         'Client for handling incoming data
Private sendingClient As UdpClient                           'Client for sending data
Private receivingThread As Thread                            'Create a separate thread to listen for incoming data, helps to prevent the form from freezing up
Private closing As Boolean = False                           'Used to close clients if form is closing

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

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Me.Load
    InitializeSender()          'Initializes startup of sender client
    InitializeReceiver()        'Starts listening for incoming data                                             
End Sub

''''''''''''''''''''Setup sender client'''''''''''''''''

Private Sub InitializeSender()
    sendingClient = New UdpClient(broadcastAddress, port)
    sendingClient.EnableBroadcast = True
End Sub

'''''''''''''''''''''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

'''''''''''''''''''Send data if send button is clicked'''''''''''''''''''

Private Sub sendBut_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles sendBut.Click
    Dim toSend As String = tbSend.Text                  'tbSend is a textbox, replace it with whatever you want to send as a string
    Dim data() As Byte = Encoding.ASCII.GetBytes(toSend)'Convert string to bytes
    sendingClient.Send(data, data.Length)               'Send bytes
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
        If closing = True Then                                       'Exit sub if form is closing
            Exit Sub
        End If
    End While
End Sub

'''''''''''''''''''Close clients if form closes''''''''''''''''''

Private Sub Form1_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing
    closing = True          'Tells receiving loop to close
    receivingClient.Close()
    sendingClient.Close()
End Sub

Here are a few other exmples: Here, here, here and here.