Introduction:
In the previous topic, a friend left me a message about P2P-related content. First of all, I am not a big fan of C # network programming. Because of the relationship between capabilities, I can only share some of my learning processes with my understanding of some of my learning processes. Next I will go to the topic-peer-to-peer programming.
I. Introduction to P2P
First of all, the well-known BT, plug-ins, Thunder, QQ, MSN, and PPLIVE are all P2P-based software, and peer to peer (P2P) it will be the development direction of the Internet, so it is very important to understand P2P technology. Next we will introduce the P2P Architecture:
Before P2P technology, all our network applications were implemented using the C/S or B/S architecture.ProgramIn, the client software sends a request to the server, and the server then responds to the client request. In this case, the more the client, the more pressure on the server. However, each Computer Implemented by P2P technology is both a client and a server, and their functions are equivalent. When a computer installed with P2P software (such as thunder and QQ) is added to a common P2P network, nodes in the network can directly transmit and communicate data.
1.1 comparison between P2P Architecture and C/S architecture
The C/S architecture has the following disadvantages (in fact, I have also discussed it in the above brief introduction ):
1. The server is overloaded. When a large number of users access the servers of the C/S system, the server is often blocked by network. At this time, we may increase investment to improve the hardware performance of the server.
2. System Robustness is closely related to servers. It means that if the server encounters a problem, the entire system will be paralyzed (it feels like the principle that is often emphasized in object-oriented systems-the low coupling principle)
However, P2P has the following features:
1. Peer-to-peer mode
The client in the P2P system can play the role of both the client and the server, so that the two computers can directly share information without passing through the server (qq when friends send messages online, it is believed that the message does not need to be forwarded by the server. Only when the message is sent to an offline friend, the message should be sent to the server for storage. When the friend logs on again, will be connected to the server, the server will judge whether the user's information is sent to determine whether to forward, the implementation of QQ Software is a hybrid P2P structure, this will be introduced in the next P2P system classification .)
Note: I personally understand the brackets. If you have any mistakes, please correct them in time so that I can update them in time to avoid misleading you. Thank you for your supervision.
2. Distributed Storage of network resources
In the C/S architecture, all clients directly download all data resources from the server, which will inevitably increase the burden on the server, while P2P changes the server-centric status, so that each node can download a part from the server first, and then download the remaining part from the other node or other nodes. In this way, when a large number of clients download at the same time, there will be no network congestion.
1.2 classification of P2P Systems
P2P systems are divided into two types: (1) P2P, with no dedicated servers. Computers installed with P2P software can communicate directly.
(2) hybrid P2P: there is a dedicated server. The server is generally called an Index Server, which is different from the server in the C/S architecture, in the C/S architecture, all resources are stored on the server, and all transmitted information must go through the server. The Indexing Server in the hybrid P2P system only provides the coordination and expansion functions, resources are not all stored on servers, but distributed on various computers. computers installed with P2P software are connected to the Indexing Server to notify them of the IP addresses and port numbers they are listening, then, the Indexing Server will tell other computers connected to them that the connection and disconnection of each computer will notify the computers connected to the network through the server, this reduces the burden on each computer to search for other computers, but the transfer of information is still done through point-to-point (QQ can be used as an example here, when P2P software such as QQ is installed on our computer, computers installed with the software such as QQ will join a P2P network and connect to the Indexing Server during login, connect to the server to inform the server of its IP address and port number. When we chat with a friend The computer will connect to the server port, but to send messages to each other, your computer must know the IP address and port number of your computer to communicate, in this way, the Indexing Server is used to inform the other party that the IP address and port number of the computer's friends are to be told, and the computer's own IP address and port number are to be told, in this way, both parties can communicate directly without passing through the server .)
1.3 mainstream P2P application classification
P2P network applications can be roughly divided into three categories: 1. file sharing, such as thunder, BT, and other software are all file sharing applications.
2. Instant Messaging, such as QQ, MSN, and other software.
3. multimedia transmission, such as online live video broadcast software and PPLIVE Software
From the above classification, we can see that all popular software on the network is implemented using P2P technology, but their implementation is certainly not simply implemented using P2P technology, it is implemented using multiple technologies. In the next topic, we will introduce the use of TCP, UDP, P2P and other technologies to implement an instant communication program similar to QQ, we hope that this program can be used to integrate the content introduced in the previous topic and help you understand the implementation principles of QQ and other software.
Ii. Basic principles of P2P
In the previous section, we briefly introduced some P2P knowledge. Through the previous introduction, I believe that everyone has a certain understanding of P2P technology, however, to develop a P2P application on your own, you must understand the implementation principles of P2P technology. The following describes the basic principles of P2P implementation.
After the P2P software is installed, both parties must first communicate with each other and be able to discover the other party (that is, know the IP address and port number of the other party). Once the other party is found, the communication can be performed, therefore, P2P applications are generally dividedDiscovery, connection, and communicationThree stages. The discovery phase is responsible for dynamically locating the network location of the contact. The connection phase is responsible for establishing network connections between the two parties, and the communication phase is responsible for transmitting data between the two parties.
2.1 discovery phase
To communicate with another computer, you must know the IP address and listening port of the other computer. Otherwise, messages cannot be sent to the other computer. In the previous C/S architecture, the IP address of the server is generally fixed, and the domain name of the computer that provides services is generally not changed, so in order to facilitate client access, some Web servers are registered in DNS (DNS is actually a ing between domain names and IP addresses). The client can use the domain name resolution mechanism to resolve the server domain name to an IP address, and then in P2P applications, each peer node (computer or resource) can be added and left at any time, and the IP address of the peer node is not fixed, therefore, the DNS mechanism cannot be used to obtain peer-to-peer node information in the P2P architecture.
Currently, in P2P protocol, the protocols and standards used by various P2P technologies are different for how to discover peer-to-peer nodes.. Net supports peer name resolution protocol (PNRP). This protocol can detect peer node information and resolve any resource to a group of IP addresses and port numbers through the serverless resolution function, the simple program implemented later uses this Protocol to complete the discovery phase.
2.2 connection and Communication phase
After discovering the peer node, you can select TCP, UDP, or other protocols as needed to complete data transmission. If you select TCP, you need to establish a connection first, and then use the connection to transmit data. For TCP content, you can view my previous topics. If you select UDP, you do not need to establish a connection, you can directly communicate with each other.
Iii. Support for P2P programming on the. NET platform
We have also introduced this in the discovery phase. NET platform for P2P programming support, and then Microsoft helped us encapsulate the implementation of the pnrp protocol, these classes in the system. net. in the peertopeer namespace (Microsoft now encapsulates a lot of things for us, so that we can easily develop applications. I feel that Microsoft is doing this, and it has helped us with the implementation of the Program, when developing programs, we only need to focus on the business logic. Of course, this method has both advantages and disadvantages. I think the advantage is to shorten the software development cycle, let us spend more time implementing the true business logic of software. The bad thing is that programmers cannot be called programmers now, so many people in the garden are called coders, my own views)
3.1 peer name resolution protocol (PNRP)
PNRP can register and resolve peer names (which can be compared with DNS ).
3.1.1 Basic Concepts
The first introduction is the concept of peer-to-peer name. We Abstract Every network resource (including resources such as computers, P2P applications, videos, MP3 files, and other documents) into peer nodes, the peer node name is of course the peer node name. The peer node name is short for the peer name. It is divided into two forms: secure and insecure. Insecure names are only composed of text strings, anyone can register an identical insecure peer name. A Secure Peer name is supported by a public/private key (representing a unique) pair. Therefore, it is not spoofed when you use PNRP for registration, the format of the Peer name is as follows:
Authority. Classifier
The value of authority depends on the security type of the name. For insecure types,AuthorityIt is a single character "0", and for Secure Peer names,AuthorityConsists of 40 hexadecimal characters
Classifier is a user-defined string used to mark a peer node. The maximum length is 150 Unicode characters. For example, the peer name 0. peernametest1 is an insecure peer name.
The second concept is the cloud concept. computers installed with the same P2P software will join a common P2P network to identify each other's resources and smoothly perform P2P communication. Microsoft's PNPR protocol calls this P2P network "Cloud ".A cloud is a set of peer nodes and their resources that can be recognized by P2P networks.All peer nodes in the cloud can resolve the locations (IP + port) of any other resources registered to the cloud, and a resource on a peer node can be registered to multiple clouds at the same time.
PNPR currently uses two types of clouds: Local cloud and global cloud. If a peer name is registered with a local cloud, it means that only other peer nodes on the same local network can resolve the name. The peer name registered on the global cloud allows the resolution of any peer node on the IPv6 internet.
Note: The global cloud is based on the IPv6 protocol and does not support IPv4 addresses. If there is no IPv6 address, the global cloud is not displayed and cannot be added to the global cloud. Because most applications on the Internet still use IPv4 addresses, we usually do not use the global cloud for P2P programming, but only the default local cloud.
3.1.2 Name Registration
To identify any resource by other computers on the network, you must first register it in the P2P network. The name registration is to publish the peer name containing peer node information to the cloud for resolution by other peer nodes. If a resource is registered in the cloud, it can be parsed and accessed by other peer nodes in the cloud.
The specific content of name registration will also be used in subsequent P2P programs.CodeTo further understand the registration of names, here we will first introduce
3.1.3 name resolution
Name resolution refers to the process of using a peer name to obtain the IP address and port number of the peer node where the cloud resources are located (the same principle as DNS resolution ).PNPR name resolution can only be used to register resources on other peer nodes in the cloud, rather than discovering registered resources.
The PNPR protocol does not use an Index Server. Therefore, to complete resolution, each peer node in the cloud stores cache records of some PNRP IDs. The PNPR cache contains both the pnpr id and the IP address and port number of the application. The name resolution step is -- first find the target resource in the cache of the peer node of the Local Computer. If no, view the target resource in the cache near the node, wait until you find the peer node where the target resource is located.
3.2 peertopeer namespace
The above mainly introduces the working process of the PNPR protocol (equivalent to the theoretical part). Next we will introduce the use of. Net to encapsulate the PNPR class for us. Here we will briefly describe the use of several common classes, and attach the link to msdn. You can click the link to view details, because the P2P program is also used in detail, so we will not list them all here.
Class Name |
Msdn Link |
PeerClass |
Http://msdn.microsoft.com/zh-cn/library/system.net.peertopeer.collaboration.peer.aspx |
CloudClass |
Http://msdn.microsoft.com/zh-cn/library/system.net.peertopeer.cloud.aspx |
PeernameClass |
Http://msdn.microsoft.com/zh-cn/library/system.net.peertopeer.peername.aspx |
PeernamerecordClass |
Http://msdn.microsoft.com/zh-cn/library/system.net.peertopeer.peernamerecord.aspx |
PeernameregistrationClass |
Http://msdn.microsoft.com/zh-cn/library/system.net.peertopeer.peernameregistration_members (V = vs.90). aspx |
PeernameresolverClass |
Http://msdn.microsoft.com/zh-cn/library/system.net.peertopeer.peernameresolver.aspx |
Basically, these classes have a general idea of their usage from the class names, so they are not described here, but they are attached with the link of msdn.
4. Implement P2P applications
The above introduces so many P2P-related knowledge, mainly to prepare for implementing a custom P2P application. Here we simply implement a Resource Discovery program.
Core code:
Peer name registration code:
// Register Resources Private Void Btnregister_click ( Object Sender, eventargs e ){ If (Tbxresourcename. Text ="" ) {MessageBox. Show ( " Enter the name of the released resource! " , " Prompt " ); Return ;} // Register the resource name in the cloud // The structure of the specific resource name is described in the blog Peername resourcename = New Peername (tbxresourcename. Text, peernametype. Unsecured ); // Use the specified name and port number to initialize the peernameregistration class instance. Resourcenamereg [seedcount] = New Peernameregistration (resourcename,Int . Parse (tbxlocalport. Text )); // Set comments for other information about the peer name object registered in the cloud Resourcenamereg [seedcount]. Comment = Resourcename. tostring (); // Set the binary data defined by the application of the peernameregistration object Resourcenamereg [seedcount]. Data = encoding. utf8.getbytes ( String . Format ( " {0} " , Datetime. Now. tostring ())); // Register peername (peer name) in the cloud) Resourcenamereg [seedcount]. Start (); seedcount ++ ; Comboxsharelist. Items. Add (resourcename. tostring (); tbxresourcename. Text = "" ;}
Name resolution code (search Resource ):
// Search Resources Private Void Btnsearch_click ( Object Sender, eventargs e ){ If (Tbxseed. Text = "" ) {MessageBox. Show ( " Enter the name of the seed resource to be searched. " , " Prompt " ); Return ;} Lstviewonlinepeer. Items. Clear (); // Initialize the resource name to be searched Peername searchseed = New Peername ( " 0. " + Tbxseed. Text ); // The peernameresolver class resolves the node name to the value of peernamerecord (the address of the resource name, including the IP address and port number, will be searched through the resource name) // Peernamerecord is used for each node on the cloud Peernameresolver myresolver = New Peernameresolver (); // Peernamerecordcollection indicates the container of the peernamerecord Element // The resolve method is synchronous completion parsing. // If you use the synchronization method, the interface may be "suspended ". // Multi-thread or asynchronous mode can be used to solve the problem of false interface death. // For more information about multithreading, see the multithreading series in my blog. I have used it in UDP programming. // I will not list the use of multithreading here. You can implement it by yourself. If you have any questions, leave a message for me to discuss. Peernamerecordcollection recordcollection = Myresolver. Resolve (searchseed ); Foreach (Peernamerecord record In Recordcollection ){ Foreach (Ipendpoint endpoint In Record. endpointcollection ){ If (Endpoint. addressfamily. Equals (addressfamily. InterNetwork) {listviewitem = New Listviewitem (); item. subitems. add (endpoint. tostring (); item. subitems. add (encoding. utf8.getstring (record. data); lstviewonlinepeer. items. add (item );}}}}
Running result:
In order to demonstrate the effect of resource discovery, three processes of this program are enabled at the same time to simulate peer-to-peer three computer nodes on the network, after you enter a resource in the Resource Name, the local shared resource is displayed in the following table. Other computers on the P2P network can search for the resource by resource name, display the obtained Resource Name and release time in the listview control. The running result of the program is as follows:
V. Summary
Now the introduction of P2P programming is over. This topic is just a simple demonstration of a Resource Discovery program. resource discovery is the core technology of P2P, it is precisely because P2P technology realizes the discovery of Internet resources that make it widely used. For example, we often use the download tool-thunder, which is a typical application that uses P2P technology, when we enter "Love apartment 3" on the thunder page (equivalent to the resource name entered in the "seeds" text box in this topic) then, after clicking search, Thunder will automatically start "dog search" and display the resource link list. When we click Connect, we can download it. However, thunder certainly does not use Microsoft's PNPR, but the Protocol independently developed by thunder, which works the same as PNPR-all of which are used to resolve the addresses of network resources. Of course, thunder also uses other technologies, such as search engines.
I hope this topic will help you understand P2P technology. If you have any questions, you can leave a message to discuss them. In the next topic, we will introduce the implementation of a program similar to QQ.
Source code attached: http://files.cnblogs.com/zhili/P2PResourceDiscovery.zip, hope to find helpful friends can be recommended. Thank you for your support.