Click here to Skip to main content
16,012,223 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 493.5K   47.9K   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

 
Questionhow to receive when receiver is behind router Pin
hafidz11-Feb-08 15:42
hafidz11-Feb-08 15:42 
QuestionASCII to Unicode conversion error? Pin
forcedfx1-Feb-08 7:06
forcedfx1-Feb-08 7:06 
QuestionUDP Send Receive [modified] Pin
Tom Chesley7-Dec-07 14:52
Tom Chesley7-Dec-07 14:52 
Questionhow to check if the data was successfully received by that IP ? Pin
sivaramireddy p4-Dec-07 19:19
sivaramireddy p4-Dec-07 19:19 
Generalhi Pin
rakeshdasgupta10-May-07 0:51
rakeshdasgupta10-May-07 0:51 
GeneralInstant Messenger Pin
chse72026-Apr-07 10:01
chse72026-Apr-07 10:01 
QuestionImage Display on UDP receive GUI Pin
bansal vipin1-Feb-07 0:11
bansal vipin1-Feb-07 0:11 
Generalclass for UDP vb.net 2005 Pin
somethingnull8-Oct-06 22:16
somethingnull8-Oct-06 22:16 
i made a somewhat easy to use class for the udp protocall using this
let me know what you think.
it needs comments though.
my spelling is not good and i am to sleepy to spell check...

you have to give Kumudu Gunasekara and me (william k.) credit if you want to use this class
-------------------------------------------------------------------------------------------

Class UdpProto
Public Structure Messageing 'use this structure to get the received messages
Dim IpAddress As Net.IPAddress
Dim Message As [Byte]()
End Structure

Public PortNumber As Integer = 1101 'any port to receive on

Private Received As New ListBox

Private udpClient As New Net.Sockets.UdpClient
Private receivingUdpClient As Net.Sockets.UdpClient
Private RemoteIpEndPoint As New _
System.Net.IPEndPoint(System.Net.IPAddress.Any, 0)
Private ThreadReceive As System.Threading.Thread

Private GLOIP As Net.IPAddress
Private GLOINTPORT As Integer
Private bytCommand As Byte() = New Byte() {}


Public Sub StartListener()

Try
receivingUdpClient = New System.Net.Sockets.UdpClient(PortNumber)
Catch ex As Exception
End Try

Try
If ThreadReceive.IsAlive = True Then Exit Sub
Catch ex As Exception
End Try
ThreadReceive = New System.Threading.Thread(AddressOf ReceiveMessages)
ThreadReceive.Start()
End Sub


Public Sub StopListener()
Try
If ThreadReceive.IsAlive = True Then
receivingUdpClient.Close()
ThreadReceive.Abort()
End If
Catch ex As Exception

End Try
End Sub


Public Sub SendMessage(ByVal ToIP As Net.IPAddress, ByVal Port As Integer, ByVal Message As [Byte]())
Dim pret As Integer
GLOIP = ToIP
GLOINTPORT = Port
udpClient.Connect(GLOIP, GLOINTPORT)
bytCommand = Message
pret = udpClient.Send(bytCommand, bytCommand.Length)

End Sub


Public Function GetMessage() As Messageing
Dim b As Byte() = {0}
Dim y As Messageing
y.IpAddress = Net.IPAddress.Parse("0.0.0.0")
y.Message = b
GetMessage = y
If Received.Items.Count > 0 Then
GetMessage = Received.Items.Item(0)
Received.Items.RemoveAt(0)
End If
End Function

Private Sub ReceiveMessages()
Dim receiveBytes As [Byte]() = receivingUdpClient.Receive(RemoteIpEndPoint)
Dim newMess As Messageing
newMess.Message = receiveBytes
newMess.IpAddress = RemoteIpEndPoint.Address
TheReceiver(newMess)
ReceiveMessages()
End Sub

Private Sub TheReceiver(ByVal Mess As Messageing)
Received.Items.Add(Mess)
End Sub




End Class





-- modified at 4:49 Monday 9th October, 2006
QuestionAny simple way to terminate this UDP receive thread? [modified] Pin
hungryjack.tw2-Aug-06 5:38
hungryjack.tw2-Aug-06 5:38 
AnswerRe: Any simple way to terminate this UDP receive thread? Pin
mironagy3-Aug-06 19:03
mironagy3-Aug-06 19:03 
QuestionLoosing Connection Pin
DannyCO26-Jul-06 4:51
DannyCO26-Jul-06 4:51 
GeneralVC++ 2005.net UDP Pin
alo_18-Jul-06 17:28
alo_18-Jul-06 17:28 
QuestionMultipule IP Pin
iabros29-Jun-06 3:49
iabros29-Jun-06 3:49 
QuestionWhat a great article Pin
Shaq31215-May-06 20:41
Shaq31215-May-06 20:41 
GeneralTCP/IP Pin
NeeruVerma13-Mar-06 19:26
NeeruVerma13-Mar-06 19:26 
QuestionThread problem? Pin
yka22-Feb-06 10:46
yka22-Feb-06 10:46 
AnswerRe: Thread problem? Pin
Alexander Rodecape14-Nov-13 8:18
Alexander Rodecape14-Nov-13 8:18 
GeneralNet 2005 Pin
dpcons7-Feb-06 13:07
dpcons7-Feb-06 13:07 
GeneralRe: Net 2005 Pin
gstarr0113-Nov-07 11:20
gstarr0113-Nov-07 11:20 
GeneralVB 2005 Pin
Steve Blencowe14-Dec-05 0:07
Steve Blencowe14-Dec-05 0:07 
GeneralNew to VB Pin
xlbder10-Oct-05 6:55
xlbder10-Oct-05 6:55 
Generalgreat stuff Pin
Oxcarz19-Jul-05 8:48
Oxcarz19-Jul-05 8:48 
GeneralGreat Article! Pin
tupacs017-Jun-05 20:00
tupacs017-Jun-05 20:00 
GeneralGood Article Pin
DeadConcrete10-Dec-04 19:53
DeadConcrete10-Dec-04 19:53 
GeneralGreat article Pin
Anonymous26-Nov-04 8:27
Anonymous26-Nov-04 8:27 

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.