Full understanding of Visual C # implementing UDP protocol

Source: Internet
Author: User
1. UDP protocol:

The User Data Protocol (UDP) is a "User Datagram Protocol". It is a connectionless protocol, which is mainly compared with the TCP protocol. We know that when using the TCP protocol to transmit data, we must first establish a connection (that is, a handshake) to transmit data. When a computer uses the UDP protocol for data transmission, the sender only needs to know the IP address and port number of the other party to send data, and does not need to connect. Of course, if you need to connect, Visual C # can also be used, but the premise is to make sure that the port number of the remote host to be connected is in the listening state, otherwise the program will encounter unnecessary errors, however, this is a superfluous practice. It not only loses the features and advantages of the UDP protocol for data transfer without connection, but also brings instability to the program running. Therefore, this method is not worth advocating.

Because UDP does not need to establish a definite connection, therefore, writing UDP-based applications is easier than writing TCP-based applications (you do not need to consider the connection and exception capture work in the program ). But it also brings a fatal disadvantage to UDP-based programs. Because UDP does not provide reliable data transmission, when computers transmit data using the UDP protocol, the sender only sends data and does not confirm whether the data is received by the other party. This will lead to the loss of some UDP protocol data packets during transmission, especially when the network quality is not satisfactory, the loss of data packets will become more serious. This is why the UDP protocol is not used to transmit important data over the network.

However, we cannot completely deny the UDP protocol because it is not suitable for transmitting data with high security requirements, but for unimportant data, or even if several data packets are lost, it does not affect the overall data, such as audio data and video data. Using UDP protocol is a very good choice. For example, many popular instant chat programs on the Internet, such as OICQ and ICQ, use UDP. At the same time, although the UDP protocol cannot guarantee data reliability, it has the advantages of low network resource overhead and fast data processing speed. Therefore, when data security requirements are not high, using UDP is also a good choice.

To sum up the above content, we can see that UDP is a non-connection-oriented network protocol, which has both advantages and disadvantages, as shown below:

1. UDP-based network applications are easy to implement, and UDP-based network applications are not prone to errors because they are less affected by the environment.

2. UDP protocol occupies a small amount of network resources and processes data quickly. Therefore, when the security requirements for data transmission over the network are not very high, its advantages are obvious. Data with low security requirements refers to the unimportant data, or even the loss of some data does not affect the overall data, such as audio data. Currently, many popular network applications are based on UDP, such as OICQ and ICQ.

3. Because it is not a connection-oriented network protocol, its shortcomings are also very obvious, sometimes even fatal. Because UDP is used to transmit data, after the data is sent, the sender does not confirm whether the sender has received the data. In this way, the transmitted data may be lost in the network, especially when the network conditions are not good, more data packets will be lost. Therefore, the UDP protocol is generally not used to transmit important data.

II. Introduction to the main use of Visual C # to send and receive UDP data packets and Its Usage:

Udpclient is the most common and critical class for implementing UDP with Visual C #. udpclient is located in the namespace system. net. in sockets, Visual C # sends and receives UDP packets through the udpclient class. Table 01 and table 02 are common udpclient methods and attributes and their brief descriptions.

Method description close UDP connection connect establish connection with remote host dropmulticastgroup exit multi-channel broadcast group joinmulticastgroup add udpclient to multi-channel broadcast group receive return UDP data packets sent by remote host send will UDP data packets are sent to the remote host

Table 01: Common udpclient methods and descriptions.

Attribute description: gets or sets a value for active. This value indicates whether a connection client with a remote host has been established to obtain or set the basic network socket. Table 02: common methods in the udpclient class and their descriptions.

1. Visual C # Use the udpclient class to send UDP Packets:

In actual use, there are two situations:

(1) Know the IP address of the remote computer:

The call syntax of the "send" method is as follows:

 public int Send (   byte[] dgram ,   int bytes ,   IPEndPoint endPoint) ;

Parameter description:

UDP data packets to be sent by dgram (expressed in byte arrays ).

The number of bytes in bytes data packets.

An endpoint is an ipendpoint that indicates the host and port to which data packets are sent.

Return the number of bytes sent.

The following is an example of using udpclient to send UDP data packets:

 IPaddress hostip = new IPaddress. parse ("remote computer ip address"); ipendpoint host = new ipendpoint (hostip, 8080); udpclient. send ("sent Byte", "sent byte length", host );

(2) Know the remote computer name ::

After you know the remote computer name, you can use the "send" method to directly send UDP packets to the specified port number of the remote host. This call method is also the easiest. The syntax is as follows:

 public int Send (   byte[ ] dgram ,   int bytes ,   string hostname ,   int port) ;

Parameter description:

UDP data packets to be sent by dgram (expressed in byte arrays ).

The number of bytes in bytes data packets.

The name of the remote host to be connected.

The remote port number to communicate.

Return the number of bytes sent.

2. Visual C # Use the udpclient class to receive UDP Packets:

The "receive" method in udpclient is used to receive UDP packets. The call Syntax of this method is as follows:

 public byte [] Receive (   ref IPEndPoint remoteEP) ;

Parameters

Remoteep is an instance of the ipendpoint class, which indicates the node that sends this packet in the network.

If you specify the port number of the remote computer to be sent to the local machine, you can also obtain the data by listening to the local port number. The following is the Information Code obtained by listening to the local port number "8080:

 server = new UdpClient ( ) ;receivePoint = new IPEndPoint (new IPAddress ( "127.0.0.1" ) , 8080 ) ;byte[] recData = server.Receive ( ref receivePoint ) ;

Iii. Visual C # architecture and functions of the system for implementing UDP-based network pair:

There are a lot of applications in the LAN. to work collaboratively, you need to ensure that the time on the client is consistent. To achieve this, the common practice is that the client reads the time from a server with a relatively correct time, to correct the local time. For example, the GPS timing system is often seen. The main function of the time pair system written in this section is to ensure the unification of the computer time and date on the LAN. The network-to-time program is divided into two parts: the server-side program and the client-side program. The specific method is to fix a computer on the same network segment as the server at the time of the peer, all computers in this network segment can read the time and date on this server and determine the local time and date based on the time and date on this server. On the server side, the program must provide the following functions:

Can receive requests from any client in the LAN

Record the computer name and time of the Request Client

Accurate server sending time and date

To achieve the following functions:

Server host or IP address can be set

Receive the time and date information sent by the server

The local time can be corrected based on the received server time and date.

Therefore, when Visual C # is used to implement a network pair, the system consists of two parts: server-side programs and client programs. Next we will first introduce the specific steps of the server-side program in the system when implementing the network pair in Visual C.

Iv. Visual C # specific steps for implementing the system's server-side program when the network is peer:

The server-side program is relatively simpler than the client program, mainly because the work of the server-side program is relatively simple

It is the time data of receiving client pair requests and sending server. In addition, the client not only needs to transmit and receive data, but also extract the server time to modify the time and date of the local computer. The following describes how to use Visual C # To implement a network-to-system server-side program.

1. Start Visual Studio. NET.

2. Select File, new, and project. The new project dialog box is displayed.

3. Set project type to Visual C # project ].

4. Set template to Windows application ].

5. In the Name text box, enter UDP peer server ].

6. Enter the E:/Vs. Net project in the location text box, and click OK.

7. In the Solution Explorer window, double-click the form1.cs file To Go To The form1.cs file editing page.

8. At the beginning of the form1.cs file, use the following imported namespace code to replace the default imported namespace code.

 using System ;using System.Drawing ;using System.Col 
 

Lections; using system. componentmodel; using system. windows. forms; using system. data; using system. net; using system. net. sockets; using system. threading; // use the thread using system in the program. text; // encoding used in the program

 

9. Switch to the form1.cs window, drag the following components into the form from the Windows Forms component in the toolbox, and perform the corresponding operations:

A label component that displays the server running information

A ListBox component named listbox1, used to display logs of client-side communication with server-side

A button component named button1. After it is dragged into the form and double-clicked, the system will generate the processing code corresponding to its click event in the form1.cs file.

10. In the Solution Explorer window, double-click the form1.cs file To Go To The form1.cs file editing page. Add the following code in the class code area of form1.cs. The following code defines global variables used in the program and creates global instances:

 Private udpclient server; private ipendpoint receivepoint; private int Port = 8080; // define the port number private int IP = 127001; // set the local IP address private thread startserver;

11. The following code replaces the initializecomponent process generated by the system.

 Private void initializecomponent () {This. listbox1 = new system. windows. forms. listBox (); this. label1 = new system. windows. forms. label (); this. button1 = new system. windows. forms. button (); this. suspendlayout (); this. listbox1.itemheight = 12; this. listbox1.location = new system. drawing. point (14, 40); this. listbox1.name = "listbox1"; this. listbox1.size = new system. drawing. size (268,220); this. listbox1.tabindex = 0; this. label1.forecolor = system. drawing. color. red; this. label1.location = new system. drawing. point (44, 10); this. label1.name = "label1"; this. label1.size = new system. drawing. size (210, 24); this. label1.tabindex = 1; this. label1.text = "When UDP is used, the server is running properly ...... "; this. button1.flatstyle = system. windows. forms. flatstyle. flat; this. button1.location = new system. drawing. point (106,278); his. button1.name = "button1"; this. button1.size = new system. drawing. size (75, 34); this. button1.tabindex = 2; this. button1.text = "clear information"; this. button1.click + = new system. eventhandler (this. button#click); this. autoscalebasesize = new system. drawing. size (6, 14); this. clientsize = new system. drawing. size (300,329); this. controls. addrange (new system. windows. forms. control [] {This. button1, this. listbox1, this. label1}); this. maximizebox = false; this. name = "form1"; this. TEXT = "UDP peer server"; this. load + = new system. eventhandler (this. form1_load); this. resumelayout (false );}

Now, the interface design and function implementation of the [UDP-to-server-side] project have been completed, as shown in Figure 01:

Figure 01: design page of The UDP peer server project

12. Add the following code after the initializecomponent process in the form1.cs file. The following code defines the process "start_server ". The function of this process is to obtain the client-side request data and send the current server time and date to the client.

 Public void start_server () {While (true) {// receives Data byte [] recdata = server from the remote host to the local port 8080. receive (ref receivepoint); asciiencoding encode = new asciiencoding (); // obtain the client request data string read_str = encode. getstring (recdata); // extract client information and store it in the string array defined as temp [] temp = read_str.split ("/". tochararray (); // display the request information of the port number listbox1.items. add ("time:" + datetime. now. tolongtimestring () + "received information :"); Listbox1.items. add ("client:" + temp [0]); listbox1.items. add ("port:" + temp [1]); // The sending server end time and date byte [] senddata = encode. getbytes (system. datetime. now. tostring (); listbox1.items. add ("sending server time! "); // Send server time server. Send (senddata, senddata. length, temp [0], int32.parse (temp [1]) to the specified port number of the remote host;}

Note: In the above Code, it is agreed that the client sends the request information to the server's 8080 port number. The server program receives the data sent to the local 8080 port number. In order to let the server program know that the client initiates a request and sends the peer information to the port number of the client, the client program designs the request information for sending the peer request. The client-side request information structure is:

Computer name +/+ client receiving information port number

In this case, if the client computer name is majinhu and the port number for receiving time data from the server is 8080, the request data sent by the client program is majinhu/8080.

After the server program receives and analyzes the request data from the client, you can use the send method of the udpclient class to accurately send the current time and date of the server to the port number specified by the client. In this way, the client can obtain the current time and date of the server by reading the specified port number, so as to correct the time and date of the client.

13. Add the following code after the "start_server" process. The following code defines the "run" process. The "run" process is used to create a thread instance and initialize the thread instance in the "start_server" process. The reason why the thread is used is that the server program needs to read the port number sent to port 8080 without interruption, and the receive method is a blocking method. The thread is used to ensure the normal operation of the server-side program:

 Public void run () {// use the local port 8080 to initialize a UDP Network Service Server = new udpclient (port); receivepoint = new ipendpoint (New IPaddress (IP), Port ); // open a thread startserver = new thread (New threadstart (start_server); // start the thread startserver. start ();}

14. add the following code after the main function in form1.cs. The following code defines the "form1_load" event. In this event, the "run" process will be called. After the server program runs, when the network pair is started:

 Private void formateload (Object sender, system. eventargs e) {// The service run ();}

15. Add the following code after the "form1_load" event in the form1.cs file. The following code defines the bu

Click Event of tton1, which is used to clear the log information displayed by the server program:

 Private void button#click (Object sender, system. eventargs e) {// clear the server-side program log listbox1.items. Clear ();}

16. Replace the dispose method in form1.cs with the following code. The function of the following code is to manually collect resources used in the program:

 Protected override void dispose (bool disposing) {try {// close the thread startserver. abort (); // clear the resource server. close () ;}catch {}; if (disposing) {If (components! = NULL) {components. Dispose () ;}} base. Dispose (disposing );}

So far, all the work of the UDP-to-server project has been completed correctly. Figure 02 "UDP-to-server-side" interface after running, the name of the client requesting the time is recorded in the log information, the port number of the data sent during the time, and the request time of the client:

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.