Classe ServicePoint
Aggiornamento: novembre 2007
Fornisce la gestione della connessione per le connessioni HTTP.
Assembly: System (in System.dll)
La classe ServicePoint gestisce le connessioni a una risorsa Internet in base alle informazioni sull'host passate nell'URI della risorsa. La connessione iniziale alla risorsa determina le informazioni gestite dall'oggetto ServicePoint, che vengono quindi condivise da tutte le richieste successive a quella risorsa.
Gli oggetti ServicePoint vengono gestiti dalla classe ServicePointManager e, se necessario, creati dal metodo ServicePointManager.FindServicePoint. Gli oggetti ServicePoint non vengono mai creati direttamente, ma vengono sempre creati e gestiti dalla classe ServicePointManager. Il numero massimo di oggetti ServicePoint che è possibile creare viene impostato dalla proprietà ServicePointManager.MaxServicePoints.
Ogni oggetto ServicePoint mantiene la propria connessione a una risorsa Internet fino a quando il relativo tempo di inattività non abbia superato il tempo specificato nella proprietà MaxIdleTime. Quando il valore MaxIdleTime di una classe ServicePoint viene superato, la classe può essere riutilizzata in un'altra connessione. Il valore predefinito di MaxIdleTime è impostato dalla proprietà ServicePointManager.MaxServicePointIdleTime.
Quando la proprietà ConnectionLeaseTimeout viene impostata su un valore diverso da -1 e il tempo specificato è trascorso, una connessione ServicePoint attiva viene chiusa una volta gestita la richiesta successiva. Tale operazione è utile in presenza di applicazioni per le quali l'apertura a tempo indefinito delle connessioni attive (impostazione predefinita), non è necessaria.
Nota: |
|---|
In condizioni di carico eccessivo, è possibile che i thread liberi nel ThreadPool in alcune applicazioni si esauriscano, con un conseguente calo di prestazioni del sistema, ad esempio tempi di transazione elevati e variabili. Per consultare alcune modifiche alla configurazione per correggere questo problema, vedere http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnpag/html/scalenetchapt17.asp: |
Nel codice di esempio riportato di seguito, viene creato un oggetto ServicePoint che si connette all' URI www.contoso.com (informazioni in lingua inglese).
// This example shows how to use the ServicePoint and ServicePointManager classes. // The ServicePointManager class uses the ServicePoint class to manage connections // to a remote host. The networking classes reuse service points for all // requests to a given URI. In fact, the same ServicePoint object // is used to issue requests to Internet resources identified by the same // scheme identifier (for example, HTTP) and host fragment (for example, www.contoso.com). // This should improve your application performance. // Reusing service points in this way can help improve application performance. using System; using System.Net; using System.Threading; using System.Text.RegularExpressions; namespace Mssc.Services.ConnectionManagement { class TestServicePoint { private static void ShowProperties (ServicePoint sp) { Console.WriteLine ("Done calling FindServicePoint()..."); // Display the ServicePoint Internet resource address. Console.WriteLine ("Address = {0} ", sp.Address.ToString ()); // Display the date and time that the ServicePoint was last // connected to a host. Console.WriteLine ("IdleSince = " + sp.IdleSince.ToString ()); // Display the maximum length of time that the ServicePoint instance // is allowed to maintain an idle connection to an Internet // resource before it is recycled for use in another connection. Console.WriteLine ("MaxIdleTime = " + sp.MaxIdleTime); Console.WriteLine ("ConnectionName = " + sp.ConnectionName); // Display the maximum number of connections allowed on this // ServicePoint instance. Console.WriteLine ("ConnectionLimit = " + sp.ConnectionLimit); // Display the number of connections associated with this // ServicePoint instance. Console.WriteLine ("CurrentConnections = " + sp.CurrentConnections); if (sp.Certificate == null) Console.WriteLine ("Certificate = (null)"); else Console.WriteLine ("Certificate = " + sp.Certificate.ToString ()); if (sp.ClientCertificate == null) Console.WriteLine ("ClientCertificate = (null)"); else Console. WriteLine ("ClientCertificate = " + sp.ClientCertificate.ToString ()); Console.WriteLine ("ProtocolVersion = " + sp.ProtocolVersion.ToString ()); Console.WriteLine ("SupportsPipelining = " + sp.SupportsPipelining); Console.WriteLine ("UseNagleAlgorithm = " + sp.UseNagleAlgorithm.ToString ()); Console.WriteLine ("Expect 100-continue = " + sp.Expect100Continue.ToString ()); } private static void makeWebRequest (int hashCode, string Uri) { HttpWebResponse res = null; // Make sure that the idle time has elapsed, so that a new // ServicePoint instance is created. Console.WriteLine ("Sleeping for 2 sec."); Thread.Sleep (2000); try { // Create a request to the passed URI. HttpWebRequest req = (HttpWebRequest)WebRequest.Create (Uri); Console.WriteLine ("\nConnecting to " + Uri + " ............"); // Get the response object. res = (HttpWebResponse)req.GetResponse (); Console.WriteLine ("Connected.\n"); ServicePoint currentServicePoint = req.ServicePoint; // Display new service point properties. int currentHashCode = currentServicePoint.GetHashCode (); Console.WriteLine ("New service point hashcode: " + currentHashCode); Console.WriteLine ("New service point max idle time: " + currentServicePoint.MaxIdleTime); Console.WriteLine ("New service point is idle since " + currentServicePoint.IdleSince ); // Check that a new ServicePoint instance has been created. if (hashCode == currentHashCode) Console.WriteLine ("Service point reused."); else Console.WriteLine ("A new service point created.") ; } catch (Exception e) { Console.WriteLine ("Source : " + e.Source); Console.WriteLine ("Message : " + e.Message); } finally { if (res != null) res.Close (); } } // Show the user how to use this program when wrong inputs are entered. private static void showUsage () { Console.WriteLine ("Enter the proxy name as follows:"); Console.WriteLine ("\tcs_servicepoint proxyName"); } public static void Main (string[] args) { int port = 80; // Define a regular expression to parse the user's input. // This is a security check. It allows only // alphanumeric input strings between 2 to 40 characters long. Regex rex = new Regex (@"^[a-zA-Z]\w{1,39}$"); if (args.Length < 1) { showUsage (); return; } string proxy = args[0]; if ((rex.Match (proxy)).Success != true) { Console.WriteLine ("Input string format not allowed."); return; } string proxyAdd = "http://" + proxy + ":" + port; // Create a proxy object. WebProxy DefaultProxy = new WebProxy (proxyAdd, true); // Set the proxy that all HttpWebRequest instances use. WebRequest.DefaultWebProxy = DefaultProxy; // Get the base interface for proxy access for the // WebRequest-based classes. IWebProxy Iproxy = WebRequest.DefaultWebProxy; // Set the maximum number of ServicePoint instances to // maintain. If a ServicePoint instance for that host already // exists when your application requests a connection to // an Internet resource, the ServicePointManager object // returns this existing ServicePoint instance. If none exists // for that host, it creates a new ServicePoint instance. ServicePointManager.MaxServicePoints = 4; // Set the maximum idle time of a ServicePoint instance to 10 seconds. // After the idle time expires, the ServicePoint object is eligible for // garbage collection and cannot be used by the ServicePointManager object. ServicePointManager.MaxServicePointIdleTime = 10000; ServicePointManager.UseNagleAlgorithm = true; ServicePointManager.Expect100Continue = true; ServicePointManager.CheckCertificateRevocationList = true; ServicePointManager.DefaultConnectionLimit = ServicePointManager.DefaultPersistentConnectionLimit; // Create the Uri object for the resource you want to access. Uri MS = new Uri ("http://msdn.microsoft.com/"); // Use the FindServicePoint method to find an existing // ServicePoint object or to create a new one. ServicePoint servicePoint = ServicePointManager.FindServicePoint (MS, Iproxy); ShowProperties (servicePoint); int hashCode = servicePoint.GetHashCode (); Console.WriteLine ("Service point hashcode: " + hashCode); // Make a request with the same scheme identifier and host fragment // used to create the previous ServicePoint object. makeWebRequest (hashCode, "http://msdn.microsoft.com/library/"); } } }
package Mssc.Services.ConnectionManagement ;
// This example shows how to use the ServicePoint and ServicePointManager
// classes. The ServicePointManager class uses the ServicePoint class to
// manage connections to a remote host. The networking classes reuse service
// points for all requests to a given URI. In fact, the same ServicePoint
// object is used to issue requests to Internet resources identified by the
// same scheme identifier (for example, HTTP) and host fragment (for example,
// www.contoso.com).
// This should improve your application performance.
// Reusing service points in this way can help improve application performance.
import System.*;
import System.Net.*;
import System.Threading.*;
import System.Text.RegularExpressions.*;
class TestServicePoint
{
private static void ShowProperties(ServicePoint sp)
{
Console.WriteLine("Done calling FindServicePoint()...");
// Display the ServicePoint Internet resource address.
Console.WriteLine("Address = {0} ", sp.get_Address().ToString());
// Display the date and time that the ServicePoint was last
// connected to a host.
Console.WriteLine(("IdleSince = " + sp.get_IdleSince().ToString()));
// Display the maximum length of time that the ServicePoint instance
// is allowed to maintain an idle connection to an Internet
// resource before it is recycled for use in another connection.
Console.WriteLine(("MaxIdleTime = " + sp.get_MaxIdleTime()));
Console.WriteLine(("ConnectionName = " + sp.get_ConnectionName()));
// Display the maximum number of connections allowed on this
// ServicePoint instance.
Console.WriteLine(("ConnectionLimit = " + sp.get_ConnectionLimit()));
// Display the number of connections associated with this
// ServicePoint instance.
Console.WriteLine(("CurrentConnections = "
+ sp.get_CurrentConnections()));
if (sp.get_Certificate() == null) {
Console.WriteLine("Certificate = (null)");
}
else {
Console.WriteLine(("Certificate = "
+ sp.get_Certificate().ToString()));
}
if (sp.get_ClientCertificate() == null) {
Console.WriteLine("ClientCertificate = (null)");
}
else {
Console.WriteLine(("ClientCertificate = "
+ sp.get_ClientCertificate().ToString()));
}
Console.WriteLine(("ProtocolVersion = "
+ sp.get_ProtocolVersion().ToString()));
Console.WriteLine(("SupportsPipelining = "
+ sp.get_SupportsPipelining()));
Console.WriteLine(("UseNagleAlgorithm = "
+ System.Convert.ToString(sp.get_UseNagleAlgorithm())));
Console.WriteLine(("Expect 100-continue = "
+ System.Convert.ToString(sp.get_Expect100Continue())));
} //ShowProperties
private static void MakeWebRequest(int hashCode, String uri)
throws InterruptedException
{
HttpWebResponse res = null;
// Make sure that the idle time has elapsed, so that a new
// ServicePoint instance is created.
Console.WriteLine("Sleeping for 2 sec.");
Thread.sleep(2000);
try {
// Create a request to the passed URI.
HttpWebRequest req = ((HttpWebRequest)(WebRequest.Create(uri)));
Console.WriteLine(("\nConnecting to " + uri + " ............"));
// Get the response object.
res = ((HttpWebResponse)(req.GetResponse()));
Console.WriteLine("Connected.\n");
ServicePoint currentServicePoint = req.get_ServicePoint();
// Display new service point properties.
int currentHashCode = currentServicePoint.GetHashCode();
Console.WriteLine(("New service point hashcode: "
+ currentHashCode));
Console.WriteLine(("New service point max idle time: "
+ currentServicePoint.get_MaxIdleTime()));
Console.WriteLine(("New service point is idle since "
+ currentServicePoint.get_IdleSince()));
// Check that a new ServicePoint instance has been created.
if (hashCode == currentHashCode) {
Console.WriteLine("Service point reused.");
}
else {
Console.WriteLine("A new service point created.");
}
}
catch (System.Exception e) {
Console.WriteLine(("Source : " + e.get_Source()));
Console.WriteLine(("Message : " + e.get_Message()));
}
finally {
if ( res != null ) {
res.Close();
}
}
} //MakeWebRequest
// Show the user how to use this program when wrong inputs are entered.
private static void ShowUsage()
{
Console.WriteLine("Enter the proxy name as follows:");
Console.WriteLine("\tcs_servicepoint proxyName");
} //ShowUsage
public static void main(String[] args) throws InterruptedException
{
int port = 80;
// Define a regular expression to parse the user's input.
// This is a security check. It allows only
// alphanumeric input strings between 2 to 40 characters long.
Regex rex = new Regex("^[a-zA-Z]\\w{1,39}$");
if (args.length < 1) {
ShowUsage();
return;
}
String proxy = args[0];
if (rex.Match(proxy).get_Success() != true) {
Console.WriteLine("Input string format not allowed.");
return;
}
String proxyAdd = "http://" + proxy + ":" + port;
// Create a proxy object.
WebProxy DefaultProxy = new WebProxy(proxyAdd, true);
// Set the proxy that all HttpWebRequest instances use.
WebRequest.set_DefaultWebProxy(DefaultProxy);
// Get the base interface for proxy access for the
// WebRequest-based classes.
IWebProxy Iproxy = WebRequest.get_DefaultWebProxy();
// Set the maximum number of ServicePoint instances to
// maintain. If a ServicePoint instance for that host already
// exists when your application requests a connection to
// an Internet resource, the ServicePointManager object
// returns this existing ServicePoint instance. If none exists
// for that host, it creates a new ServicePoint instance.
ServicePointManager.set_MaxServicePoints(4);
// Set the maximum idle time of a ServicePoint instance to 10 seconds.
// After the idle time expires, the ServicePoint object is eligible
// for garbage collection and cannot be used by the ServicePointManager
// object.
ServicePointManager.set_MaxServicePointIdleTime(10000);
ServicePointManager.set_UseNagleAlgorithm(true);
ServicePointManager.set_Expect100Continue(true);
ServicePointManager.set_CheckCertificateRevocationList(true);
ServicePointManager.set_DefaultConnectionLimit(
ServicePointManager.DefaultPersistentConnectionLimit);
// Create the Uri object for the resource you want to access.
Uri MS = new Uri("http://msdn.microsoft.com/");
// Use the FindServicePoint method to find an existing
// ServicePoint object or to create a new one.
ServicePoint servicePoint =
ServicePointManager.FindServicePoint(MS, Iproxy);
ShowProperties(servicePoint);
int hashCode = servicePoint.GetHashCode();
Console.WriteLine(("Service point hashcode: " + hashCode));
// Make a request with the same scheme identifier and host fragment
// used to create the previous ServicePoint object.
MakeWebRequest(hashCode, "http://msdn.microsoft.com/library/");
} //main
} //TestServicePoint
Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition , Windows XP Starter Edition, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98, Windows CE, Windows Mobile per Smartphone, Windows Mobile per Pocket PC
.NET Framework e .NET Compact Framework non supportano tutte le versioni di ciascuna piattaforma. Per un elenco delle versioni supportate, vedere Requisiti di sistema di .NET Framework.
Nota: