C Socket Implementation UDP Protocol Communication Sample Code

  • 2021-11-30 01:13:58
  • OfStack

Today, it took a little time to verify the communication of UDP by using Socket of C #, which laid the foundation for making a distributed communication simulation system by using UDP. As we all know, UDP is the user datagram protocol, which is at the fourth layer of the Internet reference model-transport layer. The same layer as TCP protocol provides information transmission service, but the biggest difference with TCP is that it is a connectionless and unreliable information transmission.

What is connectionless unreliable? To put it bluntly, when sending data, throw the UDP packet directly to the network 1, and ignore it if you don't accept it; When receiving the data, all the UDP packages sent to the local area will be received according to the order, and we will see who sent them after receiving them. Compared with TCP, there are less handshake connection establishment, connection maintenance, connection release and other 1 series of processes, so it has the advantages of small resource consumption and fast processing speed.

Ok, after talking a lot of nonsense, let's start talking about how to use Socket in C # for UDP communication. TCP, UDP applications can be programmed through the TCPClient, TCPListener, and UDPClient classes, and these protocol classes are also based on the System. Net. Sockets. Socket classes, regardless of the details of data transfer. However, in order to better understand Socket programming, Socket class is used to program UDP communication.

UDP application has no strict sense of the real server and client points, the relationship between the endpoints are equal, so communication only need to write a program.

The following is the code and description of the key parts:

Critical global variables


private IPEndPoint ipLocalPoint; 
private EndPoint RemotePoint; 
private Socket mySocket; 
private bool RunningFlag = false; 

Method to get native IP


private string getIPAddress() 
 { 
   //  Get the local LAN IP Address  
   IPAddress[] AddressList = Dns.GetHostByName(Dns.GetHostName()).AddressList; 
   if (AddressList.Length < 1) 
   { 
     return ""; 
   } 
   return AddressList[0].ToString(); 
 } 

Valid verification of IP and port number


private int getValidPort(string port) 
  { 
    int lport; 
    // Test whether the port number is valid  
    try 
    { 
      // Whether it is empty or not  
      if (port == "") 
      { 
        throw new ArgumentException( 
          " The port number is invalid and cannot be started DUP"); 
      } 
      lport = System.Convert.ToInt32(port); 
    } 
    catch (Exception e) 
    { 
      //ArgumentException,  
      //FormatException,  
      //OverflowException 
      Console.WriteLine(" Invalid port number: " + e.ToString()); 
      this.tbMsg.AppendText(" Invalid port number: " + e.ToString() + "\n"); 
      return -1; 
    } 
    return lport; 
  } 
 
 
  private IPAddress getValidIP(string ip) 
  { 
    IPAddress lip = null; 
    // Test IP Is it valid  
    try 
    { 
      // Whether it is empty or not  
      if (!IPAddress.TryParse(ip, out lip)) 
      { 
        throw new ArgumentException( 
          "IP Invalid, unable to start DUP"); 
      } 
    } 
    catch (Exception e) 
    { 
      //ArgumentException,  
      //FormatException,  
      //OverflowException 
      Console.WriteLine(" Invalid IP : " + e.ToString()); 
      this.tbMsg.AppendText(" Invalid IP : " + e.ToString() + "\n"); 
      return null; 
    } 
    return lip; 
  } 

Configuration of Socket


// Get this machine IP , setting UDP Port number    
ip = getValidIP(tbLocalIP.Text); 
port = getValidPort(tbLocalPort.Text); 
ipLocalPoint = new IPEndPoint(ip, port); 
 
// Define network types, data connection types, and network protocols UDP 
mySocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); 
 
// Bind network address  
mySocket.Bind(ipLocalPoint); 
 
// Get the client IP 
ip = getValidIP(tbRemoteIP.Text); 
port = getValidPort(tbRemotePort.Text); 
IPEndPoint ipep = new IPEndPoint(ip, port); 
RemotePoint = (EndPoint)(ipep); 
 
// Start 1 A new thread that executes the method this.ReceiveHandle ,  
// So that in 1 Perform data reception operations in independent processes  
 
RunningFlag = true; 
Thread thread = new Thread(new ThreadStart(this.ReceiveHandle)); 
thread.Start(); 

Receiving thread


// Definition 1 Delegation  
public delegate void MyInvoke(string strRecv); 
private void ReceiveHandle() 
{ 
  // Receive data processing thread  
  string msg; 
  byte[] data=new byte[1024]; 
  MyInvoke myI = new MyInvoke(UpdateMsgTextBox); 
  while (RunningFlag) 
  { 
     
    if (mySocket == null || mySocket.Available < 1) 
    { 
      Thread.Sleep(200); 
      continue; 
    } 
    // Calling controls across threads  
     // Receive UDP Datagram, reference parameter RemotePoint Get the source address  
     int rlen = mySocket.ReceiveFrom(data, ref RemotePoint); 
    msg = Encoding.Default.GetString(data, 0, rlen); 
    tbMsg.BeginInvoke(myI, new object[]{RemotePoint.ToString() + " : " + msg}); 
     
  } 
} 
private void btSend_Click(object sender, EventArgs e) 
{ 
  string msg; 
  msg = tbSendMsg.Text; 
  // Send UDP Data packet  
  byte[] data = Encoding.Default.GetBytes(msg); 
  mySocket.SendTo(data, data.Length, SocketFlags.None, RemotePoint); 
} 
private void UpdateMsgTextBox(string msg) 
{ 
  // Received data display  
  this.tbMsg.AppendText( msg + "\n"); 
} 

The above only need to set the local and remote IP and port number, and it is easy to realize the two-way communication of UDP. Although UDP packets can not guarantee reliable transmission, network busy, congestion and other factors may prevent packets from reaching the designated destination. But after testing, its communication is quite reliable. Don't forget that QQ also uses UDP for instant messaging.


Related articles: