Reference:
The previous topic briefly introduced some knowledge about TCP programming. Another transport layer protocol with the same UDP status as TCP, it is also the underlying Transmission Basis for many popular network applications (such as QQ, MSN, Skype, and other instant communication software transmission layers that use UDP protocol, therefore, in this topic, I will briefly introduce the working principle of UDP and UDP programming. I hope that I can get started with my friends who are new to network programming.
1. Introduction to UDP
Both UDP and TCP are the transport layer protocols built on the IP layer, but UDP is a simple,Datagram-oriented (sock_dgram)OfNo connectionProtocol, which provides a transmission service that is not necessarily reliable.
However, TCP is connection-oriented and reliable,Byte stream (sock_stream)The "no connection" means that you do not need to establish a connection with the other party before the formal communication, you can send a request directly regardless of the peer status (for example, if you view a friend through the QQ number and then send a friend adding request, you do not need to consider the peer status ). The difference between UDP and TCP can be seen from the definition. (1) the reliability of UDP is not as good as that of TCP, because a connection must be established before TCP transmission, this increases the reliability of TCP transmission. Therefore, UDP is also called an unreliable transmission protocol. For more information about TCP, see my previous blog.
There is another difference between TCP and UDP. (2) UDP cannot guarantee ordered transmission. That is, UDP cannot ensure the order in which data is sent and received.
Next let's take a look at the working principle of the UDP protocol, have a good understanding of the working principle of UDP, And the UDP programming described later is also a good foundation.
1.1 Working Principle of UDP
UDP compresses network data traffic into a datagram. Each datagram uses 8 bytes (8x8-bit = 64-bit) to describe the header information. The remaining bytes contain the specific transmission data. The UDP header (only 8 bytes) is equivalent to the TCP Header (at least 20 bytes). The UDP header consists of four fields, each of which occupies 2 bytes, specifically, the source port, destination port, User Datagram length, and checksum,
For details about the structure, see (the structure of TCP packets is also posted below to compare it with UDP datagram ):
Both UDP and TCP Protocols are used.Port NumberRetain the data transmission channels for different applications. The data sender sends UDP datagram data through the source port, while the data receiver receives data through the target port.
1.2 advantages of UDP
As mentioned above, UDP is different from TCPUnreliable, and ordered transmission cannot be guaranteedBut what are the advantages of UDP over TCP ?,
UDP has three advantages over TCP:
(1) UDP is faster than TCP.
Because UDP does not need to establish a connection with the other party or transmit confirmation, its data transmission speed is much faster than TCP. For some applications that focus on transmission performance rather than transmission integrity (such as network audio playback, on-demand video streaming, and network conferencing), UDP is more suitable because of its fast transmission speed, enable sound quality and clear picture of videos played over the network.
(2) UDP has message boundaries.
The sender of the application that transmits data over UDPProgramThe submitted packets are directly delivered to the IP layer after the header is added. The boundary of these packets is not split or merged, but the boundary of these packets is retained. Therefore, you do not need to consider message boundary issues like TCP when using UDP, in this way, UDP programming is much simpler than the data processing received by TCP. (For TCP Message Boundary Problems, refer to the relevant documents. I will not list them here)
(3) One-to-multiple transmission over UDP
Since the data transmission Department establishes a connection, you do not need to maintain the connection status. Therefore, a server can send the same information to multiple clients at the same time. UDP can be used to send messages to all client processes in the subnet at the same time by means of broadcast or multicast. The introduction of broadcast and multicast is introduced in later TCP programming.
The preceding section describes the advantages of UDP over TCP, in which speed is the most important advantage of UDP, this is also the reason why UDP is used for transmission at the transmission layer of network meetings and instant messaging software.
Ii. Support for UDP programming on the. NET platform
After introducing the advantages of UDP over TCP. develop an application based on UDP protocol under the. NET platform. NET platform also provides excellent support for UDP programming, which provides a lot of convenience for us to develop UDP-based network applications. The following is a brief introduction.. NET platform support for UDP programming (mainly introduces the classes provided to program UDP protocol ).
. The udpclient class in the. NET class library encapsulates the basic socket, so that you do not need to consider the details of the underlying socket when sending and receiving data, this provides convenience for UDP programming and improves development efficiency (I feel that net is doing this, encapsulating some underlying implementations to facilitate our calls, this also reflects the encapsulation feature of the object-oriented language, in the following UDP programming implementation part will be the use of the main method in this class, you can view msdn to view the use of other members of this class: http://msdn.microsoft.com/zh-cn/library/System.Net.Sockets.UdpClient.aspx
Iii. Specific implementation of UDP Programming
Because the UDP process does not need to establish a connection before communication, the message receiver may not know who sent the message to it. Therefore, UDP programming is divided into two modes: one is "real-name sending ", that is, the receiver can know the sender process port from the received message, and the other is "anonymous sending", that is, the receiver does not know which port the remote process sends the information. The following uses a winform program to demonstrate UDP programming:
ImplementationCode:
Using System; Using System. net; Using System. net. Sockets; Using System. text; Using System. Threading; Using System. Windows. forms; Namespace Udpclient { Public Partial Class Frmudp: FORM { Private Udpclient sendudpclient; Private Udpclient receiveupdclient; Public Frmudp () {initializecomponent (); IPaddress [] IPS = DNS. gethostaddresses ( "" ); Tbxlocalip. Text = IPS [ 3 ]. Tostring (); Int Port =51883 ; Tbxlocalport. Text = Port. tostring (); tbxsendtoip. Text = IPS [ 3 ]. Tostring (); tbxsendtoport. Text = Port. tostring ();} // Receive messages Private Void Btnreceive_click ( Object Sender, eventargs e ){ // Create a receiving socket IPaddress localip = IPaddress. parse (tbxlocalip. Text); ipendpoint localipendpoint = New Ipendpoint (localip, Int . Parse (tbxlocalport. Text); receiveupdclient = New Udpclient (localipendpoint); thread implements ETHREAD = New Thread (receivemessage); receivethread. Start ();} // Message Receiving Method Private Void Receivemessage () {ipendpoint remoteipendpoint = New Ipendpoint (IPaddress. Any, 0 ); While ( True ){ Try { // An exception occurs when receiveudpclient is disabled. Byte [] Receivebytes = receiveupdclient. Receive ( Ref Remoteipendpoint ); String Message = Encoding. Unicode. getstring (receivebytes ); // Display message content Showmessageforview (lstbxmessageview, String . Format ( " {0} [{1}] " , Remoteipendpoint, message ));} Catch { Break ;}}} // Message content display on the interface using the delegate callback mechanism Delegate Void Showmessageforviewcallback (ListBox, String Text ); Private Void Showmessageforview (ListBox, String Text ){ If (ListBox. invokerequired) {showmessageforviewcallback = Showmessageforview; ListBox. Invoke (showmessageforviewcallback, New Object [] {ListBox, text });} Else {Lstbxmessageview. Items. Add (text); lstbxmessageview. selectedindex = Lstbxmessageview. Items. Count- 1 ; Lstbxmessageview. clearselected ();}} Private Void Btnsend_click ( Object Sender, eventargs e ){ If (Tbxmessagesend. Text = String . Empty) {MessageBox. Show ( " The sent content cannot be blank. " , " Prompt " ); Return ;} // Select sending Mode If (Chkbxanonymous. Checked = True ){ // Anonymous mode (the port bound to the socket is randomly allocated by the System) Sendudpclient = New Udpclient ( 0 );} Else { // Real-name mode (the socket is bound to the specified local port) IPaddress localip = IPaddress. parse (tbxlocalip. Text); ipendpoint localipendpoint = New Ipendpoint (localip, Int . Parse (tbxlocalport. Text); sendudpclient = New Udpclient (localipendpoint);} thread sendthread = New Thread (sendmessage); sendthread. Start (tbxmessagesend. Text );} // Message sending Method Private Void Sendmessage ( Object OBJ ){ String Message = ( String ) OBJ; Byte [] Sendbytes = Encoding. Unicode. getbytes (Message); IPaddress remoteip =IPaddress. parse (tbxsendtoip. Text); ipendpoint remoteipendpoint = New Ipendpoint (remoteip, Int . Parse (tbxsendtoport. Text); sendudpclient. Send (sendbytes, sendbytes. length, remoteipendpoint); sendudpclient. Close (); // Clear the send message box Resetmessagetext (tbxmessagesend );} // Callback mechanism adopted // Use delegation to implement cross-thread interface operations Delegate Void Resetmessagecallback (textbox ); Private Void Resetmessagetext (textbox ){ // Control. invokerequired attribute representative // True if the control processing and calling threads are created on different threads; otherwise, false If (Textbox. invokerequired) {resetmessagecallback = Resetmessagetext; textbox. Invoke (resetmessagecallback, New Object [] {Textbox });} Else {Textbox. Clear (); textbox. Focus ();}} // Stop receiving Private Void Btnstop_click (Object Sender, eventargs e) {receiveupdclient. Close ();} // Clear the accept message box Private Void Btnclear_click ( Object Sender, eventargs e ){ This . Lstbxmessageview. Items. Clear ();}}}
Running result:
Real-name sending:
Run the three processes (A, B, C) of the program locally. Process C is used as the receiving process, and process a and process B send messages to process C, process A and process are bound to port 11883 and port 21883 respectively, and both are sent to port 51883. The configuration interface is as follows:
First, deselect the "anonymous" check box and click "receive" in Process C to enable the receiving thread. In the send message box of process a and process B, enterHello, I'm 1 and hello, I'm 2And then click send. In the process, you can see the messages sent from process a and process B, for example:
It can be seen that each message shows the accurate source of the message (including the IP address and port number of the message process lock)
Anonymous sending:
After the "anonymous" check box is checked, follow the previous steps to get the following results:
The result shows that the process port numbers of the message source displayed in the list are 49439 and 49440, respectively, instead of the real Port Number of the message sending process (11883 and 21883)
This UDP can only identify the IP address of the source host, but cannot know which port the message sending process is called "anonymous sending ". Just as we usually send text messages, If we pre-store the names and phone numbers in the address book and send them a message, the receiver can immediately view who sent the information (real-name mode) from the electric display. However, when a stranger sent the information or advertisement, only the electric display appears, I don't know who the other party is (anonymous mode), so QQ sends messages.
Iv. UDP broadcast and Multicast
In the preceding UDP implementation, data is sent in one-to-one (unicast) communication mode, that is, only data is sent to a process. As mentioned above, UDP can implement one-to-multiple transmission, that is, data is sent to a group of processes through broadcast and multicast. Next we will introduce the knowledge about UDP broadcast and multicast.
4.1 basic concepts of broadcast and Multicast
Although TCP can ensure reliable and orderly data transmission, TCP only supports one-to-one transmission, in addition, a separate data communication channel must be established between the sender and each receiver during transmission. If you need to implement functions such as network conferencing and on-demand network video streaming, you must send the same data packet to a large number of hosts, if the single-play mode is used for node-by-node transmission, network congestion and other problems will occur to the sender, in this case, you can consider implementing the UDP multicast mode-broadcast and Multicast (one-to-multiple communication is divided into broadcast and Multicast ).
BroadcastIt refers to sending messages to multiple computers in the subnet at the same time, and all computers in the subnet can receive messages from the sender. Each broadcast message contains a special IP addressIn the subnet, the host flag is 1 in binary format.,For example, the subnet mask is 255.255.255.0. For subnet 192.168.0, the IP address is 192.168.0.255.
Then the broadcast messages are dividedLocal broadcast and global broadcastTwo types: local broadcast refers to all computers in the subnet to send broadcast messages. Other networks are not affected by local broadcast.
The IP address is divided into two parts: the network flag and the host flag. The two parts are distinguished by the subnet mask. The host flag uses the address where all binary values are 1 as the local broadcast address. For example:
Type a network 192.168.0.0, which uses the subnet mask 255.255.0.0, the local broadcast address is:
For IPv4, global broadcast uses all IP addresses with full bits of 1, namely 255.255.255.255. This broadcast address indicates that the destination of the datagram is all devices on the network. However, because the router automatically filters out global broadcasts, therefore, using this address is meaningless.
Then, when the receiver is distributed in multiple different subnets, the broadcast is no longer applicable. In this case, it can be achieved through multicast. multicast is also called multicast, multicast sends information from a computer to a specified computer on this network or on the entire network, that is, to the computers that have joined the specified multicast group, each computer can be added to a multicast group at any time through a program, or you can exit at any time. Just like we have opened a network meeting, we can join the meeting room for a meeting at any time, you can exit the meeting at will at the end of the meeting and during the meeting.
4.2 join and exit Multicast Groups
Multicast Groups are also called multicast groups. The multicast address ranges from 224.0.0.0 to 239.20.255 Class d ip addresses (you can check this concept in Baidu encyclopedia ). Any message sent to the multicast address will be sent to all the member devices in the group. The group can be permanent or temporary. Most of the messages we use are temporary, it only exists when there are members.
When using multicast, pay attention to the TTL (time to live) settings. The TTL value indicates the maximum number of times the router can forward data. When the maximum value is reached, the data packet is discarded, the default value of TTL is 1. If it is set to 1, data can only be sent in the subnet.
Add to multicast group:
The udpclient class providesJoinmulticastgroupMethod to add a udpclient to a multicast group using the specified IPaddress. After this method is called, the basic socket will automatically send data packets to the router, used to request to become a member of a multicast group. If you become a multicast group member, you can receive the datagram of the multicast group. As for the specific method, it will be used in the subsequent implementation of UDP broadcast programs, and you can also view msdn, so I will not list it here, just to point out the role of this method, let everyone know that there is such a method to call.
Exit multicast group:
The dropmulticastgroup method of udpclient can also be used to exit multicast groups. After this method is called, the basic socket will automatically send data packets to the vro to request to exit from the specified multicast group, after the udpclient object is recycled from the group, the datagram sent to the multicast group is no longer accepted.
V. Summary
Due to time, this articleArticleI will introduce it here. As for the Program for implementing UDP broadcast, I will put it in the next topic. I also briefly introduced the concept of broadcast and multicast, I believe everyone has a simple understanding of broadcast and Multicast (broadcast groups and multicast groups are a set of IP addresses, in fact, the Program for implementing UDP broadcast is similar to the program for implementing unicast, but only one IP address can be bound to it, that is, unicast, multicast and broadcast means that the IP address to be sent is a group, and of course one-to-many transmission is realized ). The implementation of the UDP broadcast program will be shared with you in the next topic, because I am going to have dinner now. After dinner, I will continue to introduce it to you. I hope you can recommend it if you feel helpful, this gives me the motivation to continue writing. Thank you for your support.
This topic Source Code address: http://files.cnblogs.com/zhili/UDPCommunication.zip