Integration with. NET Framework 3.5)

Source: Internet
Author: User
Tags apm idn rfc

Http://msdn.microsoft.com/zh-cn/magazine/cc163356.aspx

Msdn magazine> homepage> All journals> 2007> September> networking: In line with. NET Framework 3.5

Network

Integration with. NET Framework 3.5

Mariya atanasova and Larry cleeton and Mike flasko and Amit Paka

This article discusses:

  • Socket Performance
  • Internationalized URL
  • System. net. peertopeer namespace
This article uses the following technologies:


. NET Framework

Directory socket Performance

Support for international resource identifiers

System. net. peertopeer namespace

In Microsoft. NET Framework, the system. Net namespace exposes multiple network protocols such as HTTP and SMTP. The forthcoming. NET Framework 3.5, which will be delivered along with Visual Studio 2008, codenamed "orcas", contains a variety of enhancements and features for these core network layers. In this article, we will take a look at the three key changes provided by the system. Net team:

  • High-performance Socket API
  • Support for Uri international resource identifiers
  • Peer-to-peer (P2P) namespace
The forthcoming. NET Framework 3.5 will introduce changes to the framework itself. The features described in this article are provided in Visual Studio 2008 test version 1, which can be downloaded from msdn.

Socket Performance

In. NET Framework 2.0, the system. net. Sockets namespace provides a Windows Winsock Win32
All functions of the API socket class. The class to which this feature belongs contains various methods and attributes designed for hosted code developers. On the socket, there is a group that includes send and
The receive and other synchronization methods have the ability to overload parameters for various situations. These synchronization methods are not only easy to use, but also very suitable for simple network tasks that use sockets. Socket
There is also a set of asynchronous methods based on the asynchronous programming model (APM). APM is very common in. NET Framework (for more information, see msdn.microsoft.com/msdnmag/issues/07/03/concurrentaffairs ). These asynchronous methods make the asynchronous use of socket classes relatively simple, and also provide a method to process many sockets, or to process multiple sending and receiving operations on many sockets.

2.0
The socket class is suitable for a variety of client applications that require network sockets, as well as some server and service applications. Unfortunately, some service application solutions are not applicable
The 2.0 socket class is compatible with the local language that uses Windows Winsock APIs directly. Socket 2.0
The main problem of the class is that not only does it need to allocate necessary basic objects to maintain I/O operations on a large number of sockets, but it also requires excessive CPU loops when executing a single socket I/O
The same is true for operations.

Relying on
With. NET Framework 3.5, the Common Language Runtime (CLR) can more effectively manage a large number of overlapped objects at the same time. In CLR
The overlapped object can effectively encapsulate the local Windows overlapped structure used to manage asynchronous I/O operations. Each socket in progress
Each asynchronous I/O operation has an overlapped object instance. Now you can have 6
Tens of thousands or even more connection sockets, and at the same time keep a suspended asynchronous receiving I/O operation on each socket.

2.0
The socket class of the version uses Windows I/O to complete the asynchronous I/O
Operation. This allows applications to easily expand to a large number of open sockets .. NET framework implements
System. Threading. threadpool class, which provides a thread that can read the port and complete asynchronous I/O operations. In the development of the upcoming 3.5 release
In the process of version. NET Framework, we put a lot of effort into eliminating the overhead in the code path, including reading the complete port and calling the application to complete the proxy or
The iasyncresult object sends an I/O completion event between objects.

. Net
APM in the framework is also called the begin/end mode. This is because the begin method is called to start asynchronous operations, and then
Iasyncresult object. You can provide a proxy as a parameter to the begin method. This method is called when asynchronous operations are completed. Or, a thread can wait
Iasyncresult. asyncwaithandle. When the callback is called or a waiting signal is sent, end is called.
Method to obtain the result of the asynchronous operation. This mode is flexible and easy to use, which is very common in. NET Framework.

However
Yes, you must note that if you perform a large number of asynchronous socket operations, you have to pay the price. You must create an iasyncresult for each operation.
And the object cannot be reused. Because a large amount of object allocation and garbage collection are used, this will affect the performance. To solve this problem, the new version provides another method for executing asynchronous I/O on a socket.
Method mode. This new mode does not require the allocation of Operation context objects for each socket operation.

We didn't create a new mode, but just used the existing mode and made a basic change. Now, there are some methods in the socket class that use the event-based variant to complete the model. In version 2.0, you can use the following code to start asynchronous sending on a socket:

void OnSendCompletion(IAsyncResult ar) { }IAsyncResult ar = socket.BeginSend(buffer, 0, buffer.Length,     SocketFlags.None, OnSendCompletion, state);
In the new version, you can also:

void OnSendCompletion(object src, SocketAsyncEventArgs sae) { }SocketAsyncEventArgs sae = new SocketAsyncEventArgs();sae.Completed += OnSendCompletion;sae.SetBuffer(buffer, 0, buffer.Length);socket.SendAsync(sae);
This
There are some obvious differences. Encapsulate the operation context as a socketasynceventargs object, instead of iasyncresult
Object. This application creates and manages (or even can be reused) socketasynceventargs objects. All parameters of socket operations are composed
Specifies the attributes and methods of the socketasynceventargs object. The completion status is also set by socketasynceventargs.
The property of the object. Finally, you need to use the event processing program callback to complete the method.

Institute
These changes have significantly improved system. net. sockets in. NET Framework 3.5.
Class performance and scalability. Existing applications can automatically implement two improvements. The third improvement is the new socket
Methods can only be used by modifying the application, but these methods can provide better scalability for socket-based demanding applications.

Support for international resource identifiers

A Web address is usually represented by a universal resource identifier (URI) consisting of a very limited set of characters. Generally, these addresses can only contain uppercase and lowercase letters, numbers 0 to 9, and a few other ASCII characters including commas and hyphens.

Pair
This syntax is not very convenient for regions in the world that use non-Latin character sets (such as Japanese and Hebrew. Imagine
Www.baldwinmuseumofscience.com. If you speak English, this address is easy to understand and remember. However, if you do not speak English
The URL seems to be no different from the random arrangement of symbols. If you only speak English, can you remember a long string of addresses written in Chinese?

The International Resource Identifier (or SIRI) supports non-ASCII characters, or, more accurately, Unicode/ISO 10646 characters. This means that the domain name can contain Unicode characters, that is, there can be such a URL: http: // micro-engine Hong Kong. com.

We have extended the existing system. Uri class to provide Siri support according to RFC 3987 (see faqs.org/rfcs/rfc3987.html ). For the current users, unless they specifically choose to enable the Siri function, they will not see any changes in. NET Framework 2.0 behavior. The reason is that we need to ensure that the 3.5 version is compatible with the previous version of the application.

If yes, you must make two changes. First, add the following elements to the machine. config file:

<section name="uri" type="System.Configuration.UriSection, System,                           Version=2.0.0.0, Culture=neutral,                           PublicKeyToken=b77a5c561934e089" />
Then, specify whether the international domain name (IDN) analysis should be applied to the domain name, and whether the Siri analysis rules should be applied. This can be done in machine. config on the entire computer or in APP. config of a single application, for example:

<configuration>   <uri>      <idn enabled="All" />      <iriParsing enabled="true" />   </uri></configuration>
Qi
IDN can be used to convert all Unicode tags in a domain name to their punicode equivalent. Punicode names only contain ASCII
Character, and always prefixed with "XN. This is because most DNS servers currently deployed on the Internet only support ASCII characters. Enable IDN
Only the URI. dnssafehost attribute values are affected. For micro-engine Hong Kong. com, it contains xn--g5tu63aivy37i.com, while
Uri. Host will contain Unicode characters.

Based on the DNS server you are using, there are three possible IDN values in the enabled attributes of the IDN element:

  • "All" uses the IDN name (punicode) for all domain names.
  • "Allexceptintin" will use the IDN name for all external domain names, while the Unicode name for all internal domain names. This applies only when the Intranet DNS server supports Unicode names.
  • "None" is the default value, which matches the behavior of. NET Framework 2.0.
After the Siri analysis (iriparsing enabled = "true") is enabled, the system performs normalization and character check according to the latest Siri rules in RFC 3987. When the default value is false, normalization and character check are performed according to RFC 2396 (see faqs.org/rfcs/rfc2396.html. For more information about common resource identifiers and Uri classes, see the online documentation at msdn2.microsoft.com/system.uri.

System. net. peertopeer namespace

Work
To add an exciting new namespace to. NET Framework 3.5, the system. net. peertopeer namespace is located in
In the system. net. dll program set, it provides the core build base block required to easily create peer-to-peer (P2P) applications. This namespace is based on a typical P2P
The application is designed in three phases: discovery, connection, and communication. The discovery stage is responsible for dynamically locating Peer Points and their related network locations. The connection phase establishes a network connection between peer nodes. Communication stage
It is responsible for transmitting data back and forth between Peer Points.

System. net. peertopeer
The features in the namespace provide many options to promote discovery and connection. At the same time, such as socket, httpwebrequest, and window
Supporting technologies such as the Communication Foundation peer channel can provide solutions for the Communication phase.

In
Before peers can communicate with each other, they must be able to discover each other and resolve their network locations (addresses, protocols, and ports) based on names or other types of identifiers ). Due to transient connection, DNS
Because of the lack of address records and dynamic IP addresses, It is very complicated to find and resolve the locations of peer-to-peer nodes .. The peer name resolution protocol supported in. NET Framework 3.5
(PNRP) not only helps to discover, but also resolves any resources into a group of network endpoints through serverless name resolution, so as to implement communication between peers. PNRP
Assume two core tasks: publish peer names for resolution by other Peer Points; parse peer names published by another peer point and retrieve relevant metadata (learn more about PNRP
For more information about how the protocol works, see microsoft.com/p2p ).

In
System. net. peertopeer
In a namespace, a peer name represents a communication endpoint, which can be any object (such as a computer, service, or application) that you want to associate with metadata ). There are two types of peer names: secure and not
Secure. Secure Peer names are supported by a public/private key pair. When you use PNRP for registration, this is not spoofed. Each peer name string has an authority
Followed by a period, followed by a classifier section. The Authority section is generated by a computer based on the type of the Peer name (secure or insecure ).
Classifier is a user-defined string.

For a secure peer name, the Framework automatically creates a 40-character hexadecimal string as the authority. This hexadecimal string is a hash consisting of the public key associated with the peer name, used to ensure that such peer name registration is not spoofed. The following describes how to create a security peer Name:

PeerName p = new PeerName("My PeerName", PeerNameType.Secured);
For insecure peer names, the authority component is always 0 characters. Insecure peer names are only strings and do not provide security protection:

PeerName p = new PeerName("My PeerName", PeerNameType.UnSecured);
Create
After the peer name is created, the name is associated with the relevant metadata by instantiating the peernameregistration object. A peer name usually corresponds to an IP address.
Addresses are associated, but as you will see, a peering name can also be associated with an annotation string and binary data blob. In the following code snippet
When a peerendpoint instance is added to the registration endpoint set, an IP address can be explicitly associated with the peer Name:

PeerName peerName = new PeerName("My PeerName", PeerNameType.Secured);PeerNameRegistration pnReg = new PeerNameRegistration();pnReg.PeerName = peerName;pnReg.EndPointCollection.Add(new IPEndPoint(    IPAddress.Parse("<ip address to associate with the name>"), 5000)); pnReg.Comment = "up to 39 unicode char comment";pnReg.Data = System.Text.Encoding.UTF8.GetBytes(    "A data blob up to 4K associated with the name");
Although
However, this is for peernameregistration
Class is valid, but we find that the common situation is to associate all the addresses assigned to the local computer with the peer name. To do this, make sure that
Peernameregistration. useautoendpointselection is set to true, and
Peernameregistration. endpointcollection can be added.

Now
When all relevant metadata is passed through peernameregistration
The object is assigned to the peer name. The last step is to publish the peer name to the group so that other Peer Points can resolve the name. In PNRP, only one group participates in PNRP.
It defines the scope of release or resolution for many names. When publishing a name, you must determine the group (or range) to which the name is to be published ).

PNRP

Currently, two populations are used: Link-Local Group and global group. If a peer name is published to the link-local group, the name can be resolved only by other peers on the same link. The peer name published to the Global Group
Allow anyone on the Internet to parse the name. To publish a peer name to a global group, you only need to allocate the global group to cloud. Global enumeration.
The cloud attribute of the peernameregsitration object, and then call the start method for the registered object. Once start
After the method is called, the name is published and can be parsed by a remote peer.Figure 1Displays the code used to create and publish peer names.
Figure 1 create and publish a peer name

using System;using System.Collections.Generic;using System.Text;using System.Net.PeerToPeer;namespace CreateAndPublish{    class Program    {        static void Main(string[] args)        {            // Creates a secured PeerName.            PeerName peerName = new PeerName(                "MyWebServer", PeerNameType.Secured);            PeerNameRegistration pnReg = new PeerNameRegistration();            pnReg.PeerName = peerName;            pnReg.Port = 80;//Starting the registration means the name is published //for other peers to resolve.            pnReg.Start();                        Console.WriteLine("Registration of Peer Name: {0} complete.",                 peerName.ToString());            Console.WriteLine("Press any key to stop the registration " +                             "and close the program");            Console.ReadKey();            pnReg.Stop();        }    }}
You have learned how to create and publish a peer name. Now you need to understand how to resolve the peer name. First, you need to set the peernameresolver class instance, and then use this instance for synchronization (see Figure 2) Or asynchronous resolution name. If you are parsing the name asynchronously, you must note that the same peernameresolver can be used to Parse Multiple peer names. That is to say, before the first operation is completed, you can start multiple asynchronous parsing operations for different peer names, in this way, a new parser object is not required for each parallel parsing operation.
Figure 2 synchronization name resolution
using System;using System.Collections.Generic;using System.Text;using System.Net.PeerToPeer;using System.Net;namespace SyncResolve{    class Program    {        // The application accepts the peer name to resolve as the first        // and only command line parameter.        static void Main(string[] args)        {            // Create a resolver object to resolve a peername.            PeerNameResolver resolver = new PeerNameResolver();            PeerName peerName = new PeerName(args[0]);            // Resolve the PeerName - this is a network operation and will            // block until the resolve request is completed.            PeerNameRecordCollection results = resolver.Resolve(peerName);            // Show the data returned by the resolve operation.            Console.WriteLine("Records from resolution of PeerName: {0}",                 peerName);            Console.WriteLine();            int count = 1;            foreach (PeerNameRecord record in results)            {                Console.WriteLine("Record #{0} results...", count);                Console.WriteLine("Comment:");                if (record.Comment != null)                {                    Console.WriteLine(record.Comment);                }                                Console.WriteLine("Data:");                if (record.Data != null)                {                    //Assumes the data is an ASCII formatted string                    Console.WriteLine(                        System.Text.Encoding.ASCII.GetString(record.Data));                }                Console.WriteLine("Endpoints:");                foreach (IPEndPoint endpoint in record.EndPointCollection)                {                    Console.WriteLine("\t Endpoint:{0}", endpoint);                    Console.WriteLine();                }                count++;            }            Console.ReadKey();        }    }}
In this case, you can use Figure 1And Figure 2To create and parse the peer name. Note that when you try to use the PNRP function, the name cannot be resolved from the process where the peer name is published. It should also be noted that the pnrp api described in this article uses the Windows PNRP infrastructure and is supported by Windows XP (with the PNRP update provided by support.microsoft.com/kb/920342 installed), Windows Vista and Windows Server 2008.

. Net
Framework 3.5 also introduces system. net. peertopeer. Collaboration
Namespace. Collaboration can be performed in two environments: the first is "Network Neighbor", applicable to users who have logged on to the collaboration infrastructure and are located in the same subnet. (For more information about this topic, see microsoft.com/technet/network/p2p/pnm.mspx .) The other environment is called "Contact", which applies to those who have already been added to the Windows Address Book (you can find it in the "user" directory of the "contacts" folder ). In this "Contact" environment, you do not have to be on the same subnet.

This
Both environments allow users to share applications and objects, send invitations, and receive event notifications involving other users. For example, a salesperson needs to "meet" her colleagues when waiting for a flight at the airport ". Ideally,
The salesperson should be able to open her laptop and start the company's main business line (LOB)
The application then allows the application to dynamically search for her colleagues, whether they are sitting at the airport with her or still in the office. The application must first log on to the collaboration infrastructure and specify the logon range.
In this example, peerscope. All includes both the Internet and network neighbors:

PeerCollaboration.Signin(PeerScope.All);
After logging on to the application, the application uses the following code to search for all people near the SALESPERSON:

PeerNearMeCollection peers = PeerCollaboration.GetPeersNearMe();
Pair
Peernearmecollection contains peernearme
Class. In this way, the application now has a list of all "Network neighbors" (in the form of peernearme instances. One peernearme
An instance includes an ipendpoint (IP address + port) attribute used to specify the network location or remote peer point.

To search for all contacts stored in the salesperson's address book, the application must use the following code to retrieve all contacts:

ContactManager contactManager = PeerCollaboration.ContactManager();PeerContactCollection contacts = contactManager.GetContacts();
Contactmanager represents the Windows Address Book, which is the contact repository used by the system. net. peertopeer. Collaboration infrastructure.

Now
After all the peers have been generated (by peernearme and peercontact
), The salesperson can choose to interact with whom and quickly send an invitation to everyone. In system. net. peertopeer. Collaboration

The invitation in the environment is a mechanism that requests a remote peer to start a specific application. To establish a network connection between two peer computers, one of the Peer nodes needs to actively listen on incoming data. This mechanism allows
A peer tells the other party which application to run.

Just
In the example above, the salesman wants to interact with another colleague by using the company lob application. She needs to make sure her colleagues are also running lob.
Application. Therefore, she sent an invitation to her colleague. When the system of the colleague receives the invitation, a dialog box appears in front of the user stating that a specific person wants them to start a specific application (see Figure 3). The "accept" or "reject" Invitation option is provided in the dialog box. If the recipient clicks the "accept" button, the application mentioned in the invitation will be automatically started on the recipient's computer (in this example, the lob application), and assuming that the application has been installed.

Figure 3 Invitation to start an application from a peer(Click the image to get a larger view.) Now, both systems have applications running and are ready for collaboration. In this case, the lob application uses another network technology (such as Windows Communication Foundation peer channel, socket, or HTTP) for communication.

Me
We have already explained the invitation. Now let's take a look at using system. net. peertopeer. Collaboration.
The detailed information and related code required to enable the invitation in the namespace. P2P
In terms of infrastructure, an application refers to any executable file on your computer. To support invitations, the same guid must be used on both the invitee and invitee machines.
The application is registered with the peer-to-peer collaboration infrastructure. The following code creates and registers an executable file-based application installed on a local computer:

PeerApplication application = new PeerApplication(    appGuid, "Collaboration Application", bytes, pathToApp,     arguments, PeerScope.Internet);PeerCollaboration.RegisterApplication(    application, PeerApplicationRegistrationType.AllUsers);
Connect
You can check which contact or endpoint you want to use peercollboration. applicationlaunchinfo
The invitation sent. This allows the application just started to know that it was started through an invitation from a remote peer, so that it knows that it should re-connect to the peer that sent the invitation. The method for sending the invitation can be
Call invite for the peer object returned by getpeersnearme, or call invite for the contact returned by getcontacts, as shown below:

PeerInvitationResponse pir = peerNearMe.Invite(    app, "Hello World", data);PeerInvitationResponse pir = contact.Invite(    app, "Hello World", data);
Ratio
For example, the salesman communicates with a colleague at the airport and intends to continue after the two are separated. She can add a colleague as a contact on her computer. This is done by using
Peer. addtocontactmanager from getpeersnearme
Calls the returned peer class. Once the salesperson and her colleagues add each other as contacts, they can find and interact with each other anywhere.

. Net
Collaboration API in Framework 3.5
It also allows you to share data. For example, if all the sales staff of the company want to share their business cards electronically, they can achieve this by using peer-to-peer objects. The peer object can only be queried by remote peer nodes.
View the data blob (like a file ). Various objects can be shared by range, specifying "Network neighbors" to allow users on the same subnet to view these objects, or
Internet shared so that users anywhere can view these objects. For example, to create an object and share it in the "Network Neighbor" range, you only need to use the following code:

PeerObject object = new PeerObject(    objectGuid, bytes, PeerScope.NearMe);PeerCollaboration.SetObject(object);
Status
Status and change notification are also an important aspect of P2P collaboration. For example, our salesman wants to chat with Steve as soon as he sees his colleague at the airport logging in and is free. In
The peernearme class provides
Is used to update the Peer Points in the same subnet. Any changes to the peer will trigger a call to the associated proxy and send the change information. In this way, when Steve
The salesperson will be notified when he enters or leaves the network. The required code is as follows:

PeerNearMe.PeerNearMeChanged += PeerNearMeChangedCallback;...void PeerNearMeChangedCallback(    object sender, PeerNearMeChangedEventArgs args){        // Check which PeerNearMe has changed and what the change was        // from the args parameter.}
Is
The change notification provided by the remote contact also requires several other steps: This process requires mutual trust, which means you must select to monitor this contact, and this contact must also select to allow you to monitor. Therefore, first you choose
The subscribe method is called to monitor the contact. Then, the peer you want to monitor must be added as a contact and allow you to monitor.
Set the subscribeallowed attribute on the contact
Subscriptiontype. allowed. After these steps are completed, you can track specific changes to the peer name, object, and application that you monitor.

For example, assume that our salesman wants to chat with the customer contact as soon as he sees the customer contact go online. The following code allows the salesperson to obtain necessary status changes for the customer:

custContact.PresenceChanged += ContactPresenceChangedCallback;...void ContactPresenceChangedCallback(    object sender, PresenceChangedEventArgs args){    if (args.PeerPresenceInfo.PresenceStatus ==          PeerPresenceStatus.Online)    {        // Start chatting with the customer    }}
Note
You can change the information either for a specific object or for a specific application. To objectchanged in the peerobject class
When an event is appended with a proxy, You can provide information about the changes made to the object and the source of the changed object, such as from a contact or peernearme. Similarly
The applicationchanged event in peerapplication adds a proxy to provide information related to any changes to the application.

For example, to monitor whether a specific application in a series of applications published by a contact in the contact list has changed, you must add a proxy to the applicationchanged event of the peerapplication:

peerApplication.ApplicationChanged += AppChangedCallback;...void AppChangedCallback(    object sender, ApplicationChangedEventArgs args) {    // Check what the change was and which contact and endpoint it    // originated from the args parameter.}
Now let's imagine that the salesman is going to do other things right away, so she must change her status so that the peer can know that she has no time. You can achieve this by modifying the data associated with the peercollaboration. localpresence attribute, as shown below:

PeerCollaboration.LocalPresenceInfo = new PeerPresenceInfo(    PeerPresenceStatus.Away, "Talking with Customer");
Conclusion

This article only briefly introduces some new core network functions of. NET Framework 3.5. If you can't wait to try it out, go to msdn2.microsoft.com/aa700831 to download the latest CTP version and try these new features. Please visit the blog blogs.msdn.com/wndpof the Windows Network developer platform team to learn about the latest news about system. NET and Windows network technology.

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.