SoFunction
Updated on 2025-03-07

C# Network Programming UDP

1. Overview

UDP and TCP are two commonly used transmission protocols for network communication. C# can generally implement UDP and TCP communication through Socket. Since the .NET framework encapsulates Socket through UdpClient, TcpListener, and TcpClient, making it more convenient to use. This article will explain the related applications through these encapsulated classes.

2. Basic UDP application

Unlike TCP communication, UDP communication is not divided into server and client, and the two parties to the communication are peer-to-peer. For the sake of description convenience, we refer to both parties to the sender and the receiver.

Sender:

First create a UDP object:

string locateIP = "127.0.0.1"; //Native IP
   int locatePort = 9001;   //Send port
   IPAddress locateIpAddr = (locateIP);

   IPEndPoint locatePoint = new IPEndPoint(locateIpAddr, locatePort);

   UdpClient udpClient = new UdpClient(locatePoint);

Send data:

string remoteIP = "127.0.0.1";    //Target machine IP
   int remotePort = 9002;      //Receive port
   IPAddress remoteIpAddr = (remoteIP);

   IPEndPoint remotePoint = new IPEndPoint(remoteIpAddr, remotePort);

   byte[] buffer = Encoding.(“hello”);

   (buffer, , remotePoint);

The above completes a sending task, and a more complete sending code is as follows:

public partial class FormServer : Form
 {
  private UdpClient udpClient = null;

  private void btnConnect_Click(object sender, EventArgs e)
  {
   string locateIP = "127.0.0.1";
   int locatePort = 9001;
   IPAddress locateIpAddr = (locateIP);
   IPEndPoint locatePoint = new IPEndPoint(locateIpAddr, locatePort);
   udpClient = new UdpClient(locatePoint);

    = true;
  }

  private void Send_Click(object sender, EventArgs e)
  {
   string text = ();
   string remoteIP = "127.0.0.1";
   int remotePort = 9002;
   byte[] buffer = Encoding.(text);

   if (udpClient != null)
   {
    IPAddress remoteIp = (remoteIP);
    IPEndPoint remotePoint = new IPEndPoint(remoteIp, remotePort);
    (buffer, , remotePoint);
   }

   ("Send OK");
  }
 }

Receiver:

First create a UDP object:

string locateIP = "127.0.0.1";

   int locatePort = 9002;

   IPAddress locateIpAddr = (locateIP);

   IPEndPoint locatePoint = new IPEndPoint(locateIpAddr, locatePort);

   UdpClient udpClient = new UdpClient(locatePoint);

Receive data:

IPEndPoint remotePoint = new IPEndPoint(("1.1.1.1"), 1);

  var received = (ref remotePoint);

  string info = Encoding.(received);

  string from=$” {}:{}”;

Note two points:

1. remotePoint is to obtain the sender's IP information. When defining, you can enter any legal IP and port information;

2. The Receive method is a blocking method, so it needs to be run in a new thread. The program will wait for receiving data. When a packet of data is received, the program will return. To continuously receive data, you need to repeatedly call the Receive method.

A more complete receiver code is as follows:

public partial class FormClent : Form
 {
  private UdpClient udpClient = null; 

  private void btnConnect_Click(object sender, EventArgs e)
  {
   string locateIP = "127.0.0.1";
   int locatePort = 9002;
   IPAddress locateIpAddr = (locateIP);
   IPEndPoint locatePoint = new IPEndPoint(locateIpAddr, locatePort);
   udpClient = new UdpClient(locatePoint);
   IPEndPoint remotePoint = new IPEndPoint(("1.1.1.1"), 1);

   (() =>
   {
    while (true)
    {
     if (udpClient != null)
     {
      var received = (ref remotePoint);
      string info = Encoding.(received);
      string from=$” {}:{}”; 
     }
    }
   }); 
  }
 }

3. Packet loss and out of order

When the sending end sends a packet of data, the sending is successful regardless of whether the other party receives it or not. The UDP protocol itself does not verify the reliability of the sending. (The reliability here refers to whether it is received. If the other party receives a data packet, its content is still reliable. This is guaranteed at the link layer.) At the same time, due to factors such as network delay, the packet sent first cannot be confirmed to be received first. Therefore, due to these two reasons, there are packet loss and out of order in UDP communication.

In some business scenarios, such as real-time status monitoring, it may not be sensitive to packet loss and out of order, and it may not be necessary to deal with it, but in most cases it still minds packet loss. The simple way to deal with it is to take out the fixed-length space of the packet header to store the verification information, such as the packet number. If there is a missing, the sender can be asked to resend or sort it.

4. Package data reception into events

We encapsulate UdpClent again, enable a thread to receive data, and publish the received data packets through events, which makes it more convenient to use.

namespace 
{
 public class UdpStateEventArgs : EventArgs
 {  
  public IPEndPoint remoteEndPoint;  
  public byte[] buffer = null;
 }

 public delegate void UDPReceivedEventHandler(UdpStateEventArgs args);

 public class UDPClient
 {
  private UdpClient udpClient;
  public event UDPReceivedEventHandler UDPMessageReceived;

  public UDPClient(string locateIP, int locatePort)
  {
   IPAddress locateIp = (locateIP);
   IPEndPoint locatePoint = new IPEndPoint(locateIp, locatePort);
   udpClient = new UdpClient(locatePoint);

   //After the listening is created, create a thread and start receiving information   (() =>
   {
    while (true)
    {
     UdpStateEventArgs udpReceiveState = new UdpStateEventArgs();

     if (udpClient != null)
     {
      IPEndPoint remotePoint = new IPEndPoint(("1.1.1.1"), 1);
      var received = (ref remotePoint);
       = remotePoint;
       = received;
      UDPMessageReceived?.Invoke(udpReceiveState);
     }
     else
     {
      break;
     }
    }
   });
  }
 }
}

Specific usage methods:

private void btnConnect_Click(object sender, EventArgs e)
  {
   string locateIP = "127.0.0.1";
   int locatePort = 9002;   
   UDPClient udpClient = new UDPClient(locateIP, locatePort);
    += UdpClient_UDPMessageReceived;   
  }

  private void UdpClient_UDPMessageReceived(UdpStateEventArgs args)
  {
   var remotePoint = ;
   string info = Encoding.(); 
  }

Portal:

The introduction to C# network programming series includes three articles:

(one)UDP for C# Network Programming

(two)Introduction to C# Network Programming TCP

(three)Introduction to C# Network Programming HTTP

The above is the detailed content of UDP in C# network programming. For more information about UDP in C# network programming, please pay attention to my other related articles!