Click here to Skip to main content
Licence 
First Posted 26 Nov 2004
Views 174,521
Downloads 5,330
Bookmarked 65 times

UDP Send and Receive using threads in VB.NET

By Kumudu Gunasekara | 26 Nov 2004
This article describes how to send and receive data without making the user interface to halt, in VB.NET using UDP..
2 votes, 6.1%
1

2
2 votes, 6.1%
3
8 votes, 24.2%
4
21 votes, 63.6%
5
4.58/5 - 33 votes
2 removed
μ 4.18, σa 1.87 [?]

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:

Dim udpClient As New UdpClient

How to send

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

The variables declared above are used in the code below:

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

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:

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:

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

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

About the Author

Kumudu Gunasekara

Software Developer (Senior)

Sri Lanka Sri Lanka

Member

Follow on Twitter Follow on Twitter
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

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
QuestionNot working PinmemberPeter Hawke17:06 28 Dec '11  
Questionbig time fail PinmemberMember 802528515:05 21 Jun '11  
Questionreceivev & retrive Ms access data by vb.net Pinmemberrakesh halale23:35 10 May '11  
GeneralMy vote of 5 PinmemberBayuBoy23:10 15 Sep '10  
GeneralGreate article Pinmembershaikhsamir23:14 8 May '10  
GeneralSample DEBUGGING PinmemberMember 38353878:05 24 Jan '10  
GeneralNot sending data to a static ip receiver PinmemberJack98731:06 24 Dec '09  
Questionhow to check?? Pinmemberdunk.azie18:58 29 Jul '09  
QuestionThreads PinmemberMember 461989517:09 17 Jun '09  
GeneralThis code! PinmemberMirosta150410:35 18 Nov '08  
GeneralRe: This code! Pinmembersusindran6:21 22 Apr '09  
GeneralRe: This code! Pinmembervishal108215:24 30 Apr '09  
GeneralGood article Pinmemberfindadvait23:38 3 Nov '08  
Generalclient server transfer in VB.net Pinmembersumit_87kumar18:25 1 Jun '08  
Questionhow to receive when receiver is behind router PinmemberMember 468623916:42 11 Feb '08  
QuestionASCII to Unicode conversion error? Pinmemberforcedfx8:06 1 Feb '08  
QuestionUDP Send Receive [modified] PinmemberTom Chesley15:52 7 Dec '07  
I am trying to use the project from the article
http://www.codeproject.com/KB/IP/UDP_Send_Receive.aspx
I was hoping to find an application that did both send and receive in 1 package
I am able to receive the data that I wanted i had to change ASCII to Default due to the data is not displayable characters that would make any sense
For now so I could see the received bytes I placed them in a list box
a good example of what I see in the list box is
34
0
0
0
35
0
0
0
152
135
157
0
 
What I want to to is reply back to the same client with that information
and 10 more bytes of information
 
The part I am stumpted on is the reply from the port being listened to
to the IP & port being sent from
 
modified on Saturday, December 08, 2007 4:42:43 PM

Questionhow to check if the data was successfully received by that IP ? Pinmembersivaramireddy p20:19 4 Dec '07  
Generalhi Pinmemberrakeshdasgupta1:51 10 May '07  
GeneralInstant Messenger Pinmemberchse72011:01 26 Apr '07  
QuestionImage Display on UDP receive GUI Pinmemberbansal vipin1:11 1 Feb '07  
Generalclass for UDP vb.net 2005 Pinmembersomethingnull23:16 8 Oct '06  
QuestionAny simple way to terminate this UDP receive thread? [modified] Pinmemberhungryjack.tw6:38 2 Aug '06  
AnswerRe: Any simple way to terminate this UDP receive thread? Pinmembermironagy20:03 3 Aug '06  
QuestionLoosing Connection PinmemberDannyCO5:51 26 Jul '06  

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

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

Permalink | Advertise | Privacy | Mobile
Web01 | 2.5.120210.1 | Last Updated 26 Nov 2004
Article Copyright 2004 by Kumudu Gunasekara
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid