Communication Using UDP and Visual Basic

Isn’t it amazing how the Internet has changed our way of communication? Imagine your life without email, or even Whatsapp. The Internet is, however, much larger than many people realize. Thanks to protocols, any communication on any platform is possible. Today, you will learn about UDP and see how to create an application to use it to communicate properly. Before jumping into the application, it is worth reviewing a few of the common communication protocols.

Common Protocols Used by VB Developers

A Protocol, or rather a Communication Protocol, is a set of rules that enables two or more entities to transmit information to one another. Some of the most common Protocols are:

  • TCP: TCP (Transmission Control Protocol) enables two systems to establish a connection and exchange data. TCP also guarantees delivery of data as well as that packets will be delivered in the same sequence in which they were sent.
  • IP: IP (Internet Protocol) specifies the format of packets (datagrams) and the addressing scheme.
  • UDP: UDP (User Datagram Protocol) is a connectionless protocol that is used for broadcasting messages over a network. UDP provides very, very few error recovery services.
  • POP: POP (Post Office Protocol) is a protocol used to retrieve e-mail from a mail server. Most e-mail clients make use the POP protocol, newer systems can use the newer IMAP (Internet Message Access Protocol).
  • SMTP: SMTP (Simple Mail Transfer Protocol) is a protocol for sending e-mail messages between servers.
  • HTTP: HTTP (HyperText Transfer Protocol) is the protocol used by the World Wide Web. HTTP also defines how messages should be formatted and transmitted, and what actions Web servers and browsers should take in response to the various commands.
  • FTP: FTP (File Transfer Protocol) is used protocol for exchanging files over the Internet.

Creating an UDP Program with Visual Basic

In this article, I’m going to show you how to create a Visual Basic UDP program. Actually, I’ll show you how to make two communication programs! One app will serve as a sender of the UDP messages, and the other one will serve as the receiver of the sent UDP datagrams. This will be done by creating two Console Applications.

Following is an example of what our two programs will accomplish.

UDP
Figure 1: The Sender and Receiver applications running concurrently

The Visual Basic Sender Application

This application will be used to send pieces of information via UDP. Add the following Imports statements to your UDP Sender application:

Imports System.Net.Sockets
Imports System.Text

We will be working with the Sockets class inside the .NET namespace and do some text manipulation through the System.Text class. Add the following code:

   Sub Main()

      Console.WriteLine("Sender")

      Dim UDPClient As New UdpClient()
      UDPClient.Client.SetSocketOption(SocketOptionLevel.Socket, _
         SocketOptionName.ReuseAddress, True)
      UDPClient.Connect("localhost", 11000)
      Try

         Dim strMessage As String = String.Empty
         Do

            strMessage = Console.ReadLine()
            Dim bytSent As Byte() = _
               Encoding.ASCII.GetBytes(strMessage)

            UDPClient.Send(bytSent, bytSent.Length)

         Loop While strMessage <> String.Empty
         UDPClient.Close()

      Catch e As Exception

         Console.WriteLine(e.ToString())
      End Try

      Console.WriteLine("Press Any Key to Continue")
      Console.ReadKey()

   End Sub

I created a new UdpClient object, connected to the localhost, and specified a port I would like to communicate over. It is very important that you remember the port number on your receiving client as well; otherwise, you will not be able to communicate through the port with it. Localhost is the local computer.

I then start formulating a message to be sent. In this case, the message that will be sent will be entered by the user. I encode the entered text as ASCII as we will be dealing with plain text with no special characters. As Enter is pressed in the command window, the message will be sent to the receiver that we will create now.

The Visual Basic Receiver Application

This application will be used to receive the messages through UDP. Add the following Imports to your application:

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

The only addition here is the inclusion of the System.Net namespace. It is included in here because we will be creating IPEndPoints. Add the receiving code to your application:

   Sub Main()

      Console.WriteLine("Receiver")

      Dim UDPClient As UdpClient = New UdpClient()

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

      Try

         Dim iepRemoteEndPoint As IPEndPoint = New _
            IPEndPoint(IPAddress.Any, 11000)
         Dim strMessage As String = String.Empty
         Do


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

            Console.WriteLine("This is the message you received: " _
               + strMessage)

         Loop While (strMessage <> "exit")
         UDPClient.Close()


      Catch e As Exception

         Console.WriteLine(e.ToString())
      End Try

      Console.WriteLine("Press Any Key to Continue")
      Console.ReadKey()

   End Sub

I connect to the same port as the Sender’s and then Bind it to an address. The receive method gets called to receive the message and displays it to the user.

You should be running both programs at once to see the communication in action.

I am attaching the samples here for you.

Conclusion

Using UDP for intercompany communication is quick and easy. Until next time, cheers!

Hannes DuPreez
Hannes DuPreez
Ockert J. du Preez is a passionate coder and always willing to learn. He has written hundreds of developer articles over the years detailing his programming quests and adventures. He has written the following books: Visual Studio 2019 In-Depth (BpB Publications) JavaScript for Gurus (BpB Publications) He was the Technical Editor for Professional C++, 5th Edition (Wiley) He was a Microsoft Most Valuable Professional for .NET (2008–2017).

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read