C # Socket Implementation example code for UDP protocol communication

Source: Internet
Author: User
This article mainly introduces the C # socket implementation of the UDP Protocol communication sample code, small series feel very good, and now share to everyone, but also for everyone to do a reference. Let's take a look at it with a little knitting.

Today slightly spent a little time, the use of C # socket to verify the UDP communication, for the next special use of UDP to do a distributed communication simulation system to lay the foundation. As we all know, UDP is the User Datagram Protocol, the fourth layer of the Internet Reference Model-the transport layer. The same layer as the TCP protocol, is the transmission service to provide information, but the biggest difference with TCP is that it is a non-connected unreliable information transmission.

What is no connection unreliable? Straightforward point is that, when sending data, the UDP packet directly to the network a throw on the finished, not accept received sent on the ignore; when receiving data, there is a local UDP packet to the full receipt, and then see who sent. Compared to TCP, less handshake to establish a connection, maintenance connection, connection release and other a series of processes, it has a very small resource consumption and processing speed of the advantages.

Okay, here's a bunch of crap. How to use the socket in C # for UDP communication. TCP, UDP applications can be programmed through the TcpClient, TcpListener, and UdpClient classes, which are also based on the System.Net.Sockets.Socket class, regardless of the details of the data transfer. To better understand socket programming, however, the socket class is used to program UDP communication.

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

Here is a key part of the code and description:

Key global Variables

Private IPEndPoint Iplocalpoint; Private EndPoint Remotepoint; Private Socket Mysocket; private bool Runningflag = false;

Methods to get local IP

private string getipaddress ()  {    //Get native LAN IP address    ipaddress[] AddressList = Dns.gethostbyname ( Dns.gethostname ()). AddressList;    if (Addresslist.length < 1)    {      return "";    }    Return addresslist[0]. ToString ();  }

Effective authentication of IP and port number

private int Getvalidport (string port) {int lport; Test whether the port number is valid try {//Is empty if (port = = "") {throw new ArgumentException ("Invalid port number       , cannot start the DUP ");     } Lport = System.Convert.ToInt32 (port); } catch (Exception e) {//argumentexception,//formatexception,//overflowexception Cons Ole.       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 whether the IP is valid try {//Is empty if (!       Ipaddress.tryparse (IP, out lip)) {throw new ArgumentException ("Invalid IP, cannot 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 the socket

Get the native IP, set the UDP port number   IP = getvalidip (tblocalip.text); port = Getvalidport (tblocalport.text); iplocalpoint = new IPEndPoint (IP, port);  Define the network type, data connection type and network protocol 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);  Starts a new thread, executes the method of this. Receivehandle,//To perform the operation of data reception in a separate process  Runningflag = true; Thread thread = new Thread (The new ThreadStart (this). Receivehandle)); Thread. Start ();

Receive thread

//defines a delegate 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     }//cross-thread call control//Receive UDP datagram, reference parameter remotepoint get 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 packet byte[] data = Encoding.Default.GetBytes (msg); Mysocket.sendto (data, data. Length, Socketflags.none, Remotepoint); } private void Updatemsgtextbox (String msg) {//Receive data Display This.tbMsg.AppendText (msg + "\ n");} 

Above just set up the local and remote IP and port number, it is easy to implement UDP two-way communication. Although UDP packets can not guarantee reliable transmission, network busy, congestion and other factors, it is possible to prevent packets to reach the specified destination. But after testing, its communication is quite reliable, do not forget that QQ is also the use of UDP for instant communication.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.