Home » How - To / Tutorial » Programming » Creating Simple UDP Server And Client to Transfer Data Using C# / VB.net

Creating Simple UDP Server And Client to Transfer Data Using C# / VB.net

Transfer-file-over-the-internet Creating Simple UDP Server And Client to Transfer Data Using C# / VB.net

Transfer file over the internet

By using simple network applications, we can send files or messages over the internet. A socket is an object that symbolize a low-level connection point to the IP stack. This socket can be opened or closed or one of a set amount of intermediate states. A socket can deliver and receive data down this connection. Files is generally sent in blocks of a few kilobytes at a time for effectiveness; each of these blocks is named as a packet . Here are the list of well-known port numbers which usually used.

  • Port 20, FTP Data
  • Port 21, FTP Control
  • Port 25, SMTP (email and outgoing)
  • Port 53, DNS
  • Port 80, HTTP (Web)
  • Port 110, POP3 (email, incoming)
  • Port 143, IMAP (email, incoming)

All packets that travel on the web must use the Internet communications protocol. This means that the source IP address, destination address must be provided in the packet. Some data packets also contain a port number. A port is simply a number around 1 and 65,535 that is used to differentiate higher protocols, such as email or FTP. Ports are crucial when it comes to developing your own network applications because no two software applications can use the same port. It is advised that experimental programs use port numbers above 1024.

Packets that contain port numbers come in two flavors: UDP and TCP/IP. UDP has lower latency than TCP/IP, especially on startup. Where data integrity is not of the utmost concern, UDP can prove easier to use than TCP, but it should never be used where data integrity is more important than performance; however, data sent via UDP can sometimes arrive in the wrong order and be effectively useless to the receiver. TCP/IP is more complex than UDP and has typically longer latencies, but it does guarantee that data does not become corrupted when traveling over the Internet. TCP is best suited for file transfer (TCP/IP File Transfer), where a corrupted file is more unacceptable than a slow download; however, it is unsuited to Internet radio, where the odd sound out of place is more acceptable than long gaps of silence.

Creating a simple Send/Receive application in C# and VB.net

This program will send the words “hello world” over a network. It consists of two executables, one a server, the other a client. These two programs could be physically separated by thousands of kilometers, but as long as the IP addresses of both devices are known, the principle still works. In this example, the data will be delivered using UDP. This means that the words “hello world” will be included with information that will be used by IP routers to make sure that the data can travel anywhere it wishes in the world. UDP data is not included with headers that track message reliability or security. Moreover, the receiving end is not obliged to reply to the sender with acknowledgments as each packet arrives. The elimination of this demand allows UDP data to travel with much lower latency than TCP. UDP is useful for small payload transfers, where all of the data to be sent can be contained within one network packet. If there is only one packet, the out-of-sequence problems related with UDP do not apply; therefore, UDP is the underlying protocol behind DNS.

Creating a simple UDP client in C# and VB.net

To get started, open Visual Studio .NET, click New Project, then click Visual C# projects, and then Windows Application. Set the name to “ UDP Client ” and press OK. You could alternatively click Visual Basic .NET projects and follow the code labeled VB.NET in the examples.

UDP-client-interface Creating Simple UDP Server And Client to Transfer Data Using C# / VB.net

UDP client interface

 

Now, build the form interface as shown above. Name the button button1 and the textbox txtbHost . Click the button and type in the source code as follows:

C# Programming Language

VB.net

From the code, we can see that the first task is creating a UDP Client object. This is a socket that can send UDP packets. A port number is selected arbitrarily. Here, the port number 8080 is used, mainly because it is easy to remember and it is not in the first 1024 port numbers, which are reserved for specific use by IANA.

The first argument in the Connect method shows where any data should be sent. Here, I have used txtbHost.Text (i.e., whatever is typed into the textbox). If you have access to only one computer, you would type localhost into this window; otherwise, if you are using two devices, type the IP address of the server. You also need to include some assemblies by adding these lines to just under the lock of the using statements at the top of the code: Now, press F5 to compile and run the application. You should see your application resembling UDP client interface image.

Creating a simple UDP server in C# and VB.net

The purpose of the UDP server is to detect incoming data sent from the UDP client. Any new data will be displayed in a list box. As before, create a new C# project, but with a new user interface, as shown below. The list box should be named lbConnections . A key feature of servers is multithreading (i.e., they can handle hundreds of simultaneous requests).

In this case, our server must have at least two threads: one deals with incoming UDP data, and the main thread of execution may continue to maintain the user program interface, so that it does not appear hung.

First, we create the UDP data handling thread:

C# Programming language

VB.net

Again, we use the UdpClient object. Its constructor indicates that it should be bound to port 8080, like in the client. The Receive method is blocking (i.e., the thread does not continue until UDP data is received). In a real-world application, appropriate timeout mechanisms must be in place because UDP does not ensure packet delivery integrity. Once received, the data is in byte array format, which is then converted to a string and displayed onscreen in the form source address: data .

There is then the matter of actually invoking the serverThread method asynchronously, such that the blocking method, Receive , does not hang the application. This is fixed using threads as follows:

C# Programming Language

VB.net

Note : It’s unsafe to call directly from a worker thread (InvalidOperationException will show up in debugger), To make safe Thread-safe calls you need to use InvokeRequired check. Here’s how to do thread-safe calls

To finish off, the following assemblies are to be added:

C#

VB.net

To test this program, execute it from Visual Studio .NET. On the same computer, start the UDP client and execute it. Input localhost into the textbox and press the button on the UDP client. A message “Localhost:Hello World?” should appear, such as shown below.

UDP-Server-Interface Creating Simple UDP Server And Client to Transfer Data Using C# / VB.net

UDP Server Interface

If you have a other PC, get its IP address and set up the server on this second PC and execute it. Again open the client, but type the IP address into the textbox. When you click the button on the client, the server should display the “Hello World” message. And That’s it !! You have used .NET to deliver data across a network. If you got error while compiling maybe you have to check for common errors.

15 thoughts on “Creating Simple UDP Server And Client to Transfer Data Using C# / VB.net

  1. Peace says:

    Thank you! Thank you! This article is really going to help me. I was looking for something like this for almost 3 days. Thanks to you, I can now send info from tablet to pc! 🙂

  2. Peace says:

    Hey there, may i ask a question? When i run the “Server App” and close it, it keeps working background and i can’t run it again until i close it from task manager. I tried adding “thdUDPServer.Abort()” to formclosing event, but it still working background.

    1. Kim says:

      thdUDPServer.Abort() only make the thread stop processing. To close the program maybe you can use Exit()

  3. Peace says:

    Thanks again. I used “End” in formclosed event, looks like it solved the problem. 🙂

  4. tiguer says:

    Hey. I got an error in the server app. I can recive the data but I can not show it. I try to show it with a list Box and with a label but it doesn’t work. Can you help me please

    1. Kim says:

      If you followed this tutorial, Check your string returnData or whatever you named it. if it’s null then you need to trace the problem from there

  5. Adme says:

    Hi i would like to create a client in C# and server in VB or vice-versa but this code is not working. I would appreciate if you would suggest a solution.

    1. Kim says:

      Can you explain why it’s not working? Try to post your code here

  6. Adme says:

    Hi Kim thanks for reply!
    I have got an error massage in VB pointing on this line: Dim udpClient As New UdpClient(8080).
    The error is saying “Only one usage of each socket address (protocol/network address/port) is normally permitted”(Socket Exception was unhanded). Please find the code i used in both C# and VB below-
    Note:I used Windows Forms Application when creating the respective projects.

    Code of UDP client in C# :

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Threading.Tasks;
    using System.Windows.Forms;
    using System.Threading;
    using System.Net;
    using System.Net.Sockets;
    using System.Text;

    namespace WindowsFormsApplication1
    {
    public partial class Form1 : Form
    {
    public Form1()
    {
    InitializeComponent();
    }

    private void Lable_Click(object sender, EventArgs e)
    {

    }

    private void button1_Click(object sender, System.EventArgs e)
    {
    UdpClient udpClient = new UdpClient();
    udpClient.Connect(txtbHost.Text, 0);
    Byte[] senddata = Encoding.ASCII.GetBytes(“Hello World”);
    udpClient.Send(senddata, senddata.Length);
    }
    }
    }

    Code of UDP Server in VB :

    Imports System.Threading
    Imports System.Net
    Imports System.Net.Sockets
    Imports System.Text
    Imports System.Net.Sockets.SocketException
    Public Class Form1
    Public Sub serverThread()
    Dim udpClient As New UdpClient(8080)
    While True
    Dim RemoteIpEndPoint As New IPEndPoint(IPAddress.Any, 0)
    Dim receiveBytes As Byte()
    receiveBytes = udpClient.Receive(RemoteIpEndPoint)
    Dim returnData As String = _
    Encoding.ASCII.GetString(receiveBytes)
    lbConnections.Items.Add( _
    RemoteIpEndPoint.Address.ToString() + “:” + _
    returnData.ToString())
    End While

    End Sub
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    Dim thdUDPServer = New Thread(New ThreadStart(AddressOf serverThread))
    thdUDPServer.Start()
    End Sub
    End Class

    1. Kim says:

      Hi Adme,

      Try to use other port beside 8080 (for example, Dim udpClient As New UdpClient(8071)) and make sure both client and server use same port to communicate.

      Thanks

      1. Adme says:

        Hi Kim,

        I tried with other port addresses, unfortunately it is not working.

        Thanks!

  7. Kim says:

    Hi Adme,

    Make sure you already checked all of these
    1. Port are not blocked by firewall.
    2. Port are not used by other apps.
    3. Sometimes port used by your previous program launch, make sure you close the port before using it again.
    4. Or maybe you invoke listenPort twice on different thread.

    Thanks

  8. Luciller says:

    I like the efforts you have put in this, thank you for all the great blog posts.

  9. Christina Pole says:

    I just like the helpful info you supply to your articles.
    I will bookmark your weblog and test once more here regularly.
    I am somewhat sure I will be informed lots of new stuff proper here!
    Good luck for the following!

  10. Mathew Vodopich says:

    Have you ever considered writing an ebook or guest authoring on other blogs? I have a blog based on the same ideas you discuss and would really like to have you share some stories/information. I know my viewers would appreciate your work. If you are even remotely interested, feel free to send me an e mail.

Leave a Reply to Peace Cancel reply

Your email address will not be published. Required fields are marked *

Name *
Email *
Website