Click here to Skip to main content
15,867,568 members
Articles / Programming Languages / Visual Basic
Article

UDP Send and Receive using threads in VB.NET

Rate me:
Please Sign up or sign in to vote.
4.63/5 (50 votes)
26 Nov 20042 min read 486.2K   47.6K   73   57
This article describes how to send and receive data without making the user interface to halt, in VB.NET using UDP..

Image 1

Image 2

Introduction

When I first started with network programming I was unable to get a clean networking project without all the advanced stuff, that is why I'm submitting this. This article introduces how to use UDP/IP to send and receive data between two computers in a network. This also demonstrates the use of threads to send and receive data so that the user interface doesn't get stuck while sending and receiving data. In the receive program there is a cool section which converts the received message to bit format. That is also a simple technique which anybody can understand.

Anybody can use this program in a fair manner. And if you want to add more advanced features feel free to ask. I'm also going to submit a TCP/IP VC++.NET version of this program so that it may be more useful to you.

Background

This program uses UdpClient to send and receive data. This means that it uses the User Datagram Protocol to communicate. The main advantage of UDP is that it works three times faster than TCP. But beware if you are using an unreliable network, data loss can occur.

Using UDP

When using UDP in VB.NET you must first create a UdpClient like this. Make sure you import Imports System.Net.Sockets in the project:

VB
Dim udpClient As New UdpClient

How to send

VB
Dim GLOIP As IPAddress 
Dim GLOINTPORT As Integer 
Dim bytCommand As Byte() = New    Byte() {}

The variables declared above are used in the code below:

VB
GLOIP = IPAddress.Parse(txtIP.Text)
GLOINTPORT = txtPort.Text
udpClient.Connect(GLOIP, GLOINTPORT)
bytCommand = Encoding.ASCII.GetBytes(txtMessage.Text)
pRet = udpClient.Send(bytCommand, bytCommand.Length)
Console.WriteLine("No of bytes send " & pRet)

First of all, we have to assign an IP address to the GLOIP variable. In VB.NET we use IPAddress.Parse(" ") to get the IP address from a String. Of course getting the port is as simple as assigning the value.

Then we use the UdpClient.Connect(hostname as String, port as integer) to connect.

Then comes the tricky part, converting the string message to the Byte() format. Once you do this, you just have to use the UdpClient.Send() method to send the data and it will pass an integer value indicating the number of bytes send.

How to receive

VB
Public receivingUdpClient As UdpClient
Public RemoteIpEndPoint As New _
      System.Net.IPEndPoint(System.Net.IPAddress.Any, 0)
Public ThreadReceive As System.Threading.Thread
Dim SocketNO As Integer

The variables declared above are used in the code below:

VB
SocketNO = txtSocket.Text
receivingUdpClient = New System.Net.Sockets.UdpClient(SocketNO)
ThreadReceive = _
   New System.Threading.Thread(AddressOf ReceiveMessages)
ThreadReceive.Start()

The above code is placed wherever you want to start the receive process. The code starts the thread to receive so that the interface doesn't get stuck by waiting for the receive. The thread assigns ReceiveMessage function to do the receive process.

Here is the basic coding in the ReceiveMessage function:

VB
Dim receiveBytes As [Byte]() = receivingUdpClient.Receive(RemoteIpEndPoint)
txtIP.Text = RemoteIpEndPoint.Address.ToString
Dim BitDet As BitArray
BitDet = New BitArray(receiveBytes)
Dim strReturnData As String = _
            System.Text.Encoding.Unicode.GetString(receiveBytes)

This code receives the message. As you can see in the coding the IPEndPoint is configured so that it will receive from any IP address. The receiving port is assigned during the thread calling time.

This also demonstrates the conversion of Byte() to String so that you can do whatever you like with the received message.

How to get the bit details

VB
For j = 0 To BitDet.Length - 1
    If BitDet(j) = True Then
        Console.Write("1 ")
        tempStr2 = tempStr
        tempStr = " 1" + tempStr2
    Else
        Console.Write("0 ")
        tempStr2 = tempStr
        tempStr = " 0" + tempStr2
    End If
    i += 1
    If i = 8 And j <= (BitDet.Length - 1) Then
        line += 1
        i = 0
        TextBox1.Text = TextBox1.Text + tempStr
        tempStr = ""
        tempStr2 = ""
        TextBox1.Text = TextBox1.Text + vbCrLf
        If j <> (BitDet.Length - 1) Then
            TextBox1.Text = TextBox1.Text + line.ToString & ") "
            Console.WriteLine()
        End If
    End If
Next

This simple code gets the message bit pattern and pastes it in a textbox. Make sure that the Multiline property of the text box is set to True.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Software Developer (Senior)
Sri Lanka Sri Lanka
I'm a software engineer working in a leading IT company in Sri Lanka. I'm a Microsoft Certified Technology Specialist. I used to submit articles that I taught would benefit fellow programmers. Unfortunately my last submission was more than 7 years ago. I'm thinking about starting again soon. Check out my full bio
My web site

Comments and Discussions

 
QuestionUDP HEX send and read Pin
Сергей Егоров1-Jan-23 7:40
Сергей Егоров1-Jan-23 7:40 
Questionhow to set priority to your message Pin
chakirchakir20-Feb-18 6:13
chakirchakir20-Feb-18 6:13 
Questionbut how to send udp command to syslog to local 6 Pin
chakirchakir20-Feb-18 0:37
chakirchakir20-Feb-18 0:37 
QuestionRegarding packet receiving and auto storing in Vb using udp Pin
Member 1327684426-Jun-17 18:38
Member 1327684426-Jun-17 18:38 
Questionbidirectional UDP conection Pin
garben1221-Jan-17 0:36
garben1221-Jan-17 0:36 
Hi Kumudu and all,
this was very helpful. I was a VB 6 programmer and had quite a few problems getting into .NET.
This helped a lot for my UDP applications. I have still a problem regarding the mutual send and receive activities. How can I build on this code to make both Computers capable to sedn and receive from each other?
Thanks
Gary
QuestionThanks Pin
Ralf Meier6-Aug-16 10:05
professionalRalf Meier6-Aug-16 10:05 
QuestionVery good Pin
Nattawutxp11-Sep-14 22:28
Nattawutxp11-Sep-14 22:28 
QuestionHelp sending Hex in the send box instead of text Pin
Member 109991077-Aug-14 12:48
Member 109991077-Aug-14 12:48 
QuestionSource of the message Pin
Dev O'Connor20-Mar-14 13:03
Dev O'Connor20-Mar-14 13:03 
QuestionSend working but receive isn't Pin
Henry Ing-Simmons5-Aug-13 4:11
Henry Ing-Simmons5-Aug-13 4:11 
AnswerRe: Send working but receive isn't Pin
Alexander Rodecape14-Nov-13 6:37
Alexander Rodecape14-Nov-13 6:37 
GeneralRe: Send working but receive isn't Pin
Greg Criniti25-Jan-14 6:19
Greg Criniti25-Jan-14 6:19 
GeneralRe: Send working but receive isn't Pin
Alexander Rodecape30-May-14 10:26
Alexander Rodecape30-May-14 10:26 
QuestionBRAVO!!!! Pin
DrikosRikos19-Jul-13 23:09
DrikosRikos19-Jul-13 23:09 
QuestionIs this normal? Pin
Member 1000503822-Apr-13 5:44
Member 1000503822-Apr-13 5:44 
QuestionCross Thread operation Not Valid Pin
yugastio30-Dec-12 12:37
yugastio30-Dec-12 12:37 
QuestionNot working ! Pin
ayman.metwally@gizasystems.com26-Oct-12 1:02
ayman.metwally@gizasystems.com26-Oct-12 1:02 
Questionport=11000 Pin
sepide736927-May-12 1:06
sepide736927-May-12 1:06 
QuestionNot working Pin
Peter Hawke28-Dec-11 16:06
Peter Hawke28-Dec-11 16:06 
Questionbig time fail Pin
Member 802528521-Jun-11 14:05
Member 802528521-Jun-11 14:05 
Questionreceivev & retrive Ms access data by vb.net Pin
rakesh halale10-May-11 22:35
rakesh halale10-May-11 22:35 
GeneralMy vote of 5 Pin
BayuBoy15-Sep-10 22:10
BayuBoy15-Sep-10 22:10 
GeneralGreate article Pin
shaikhsamir8-May-10 22:14
shaikhsamir8-May-10 22:14 
GeneralSample DEBUGGING Pin
Member 383538724-Jan-10 7:05
Member 383538724-Jan-10 7:05 
GeneralNot sending data to a static ip receiver Pin
Jack987324-Dec-09 0:06
Jack987324-Dec-09 0:06 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.