Export (0) Print
Expand All

ServicePoint Class

Provides connection management for HTTP connections.

Namespace: System.Net
Assembly: System (in system.dll)

public ref class ServicePoint
public class ServicePoint
public class ServicePoint
Not applicable.

The ServicePoint class handles connections to an Internet resource based on the host information passed in the resource's Uniform Resource Identifier (URI). The initial connection to the resource determines the information that the ServicePoint object maintains, which is then shared by all subsequent requests to that resource.

ServicePoint objects are managed by the ServicePointManager class and are created, if necessary, by the System.Net.ServicePointManager.FindServicePoint method. ServicePoint objects are never created directly but are always created and managed by the ServicePointManager class. The maximum number of ServicePoint objects that can be created is set by the ServicePointManager.MaxServicePoints property.

Each ServicePoint object maintains its connection to an Internet resource until it has been idle longer than the time specified in the MaxIdleTime property. When a ServicePoint exceeds the MaxIdleTime value, it can be recycled to another connection. The default value of MaxIdleTime is set by the ServicePointManager.MaxServicePointIdleTime property.

When the ConnectionLeaseTimeout property is set to a value other than -1, and after the specified time elapses, an active ServicePoint connection is closed after it services the next request. This is useful for applications that do not require active connections that are opened indefinitely, as they are by default.

NoteNote:

In high load conditions, some applications may run out of free threads in the ThreadPool, which may lead to poor system performance (such as high and variable transaction times). See http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnpag/html/scalenetchapt17.asp for a number of configuration changes you can make to fix this issue.

The following code example creates a ServicePoint object that connects to the URI www.contoso.com.

// 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.dll>

using namespace System;
using namespace System::Net;
using namespace System::Threading;
using namespace System::Text::RegularExpressions;
void ShowProperties( ServicePoint^ sp )
{
   Console::WriteLine( "Done calling FindServicePoint()..." );
   
   // Display the ServicePoint Internet resource address.
   Console::WriteLine( "Address = {0}", sp->Address );
   
   // Display the date and time that the ServicePoint was last 
   // connected to a host.
   Console::WriteLine( "IdleSince = {0}", sp->IdleSince );
   
   // 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 = {0}", sp->MaxIdleTime );
   
   Console::WriteLine( "ConnectionName = {0}", sp->ConnectionName );
   
   // Display the maximum number of connections allowed on this 
   // ServicePoint instance.
   Console::WriteLine( "ConnectionLimit = {0}", sp->ConnectionLimit );
   
   // Display the number of connections associated with this 
   // ServicePoint instance.
   Console::WriteLine( "CurrentConnections = {0}", sp->CurrentConnections );
   
   if ( sp->Certificate == nullptr )
      Console::WriteLine( "Certificate = (null)" );
   else
      Console::WriteLine( "Certificate = {0}", sp->Certificate );

   if ( sp->ClientCertificate == nullptr )
      Console::WriteLine( "Client Certificate = (null)" );
   else
      Console::WriteLine( "Client Certificate = {0}", sp->ClientCertificate );

   Console::WriteLine( "ProtocolVersion = {0}", sp->ProtocolVersion->ToString() );
   Console::WriteLine( "SupportsPipelining = {0}", sp->SupportsPipelining );
   
   Console::WriteLine( "UseNagleAlgorithm = {0} ", sp->UseNagleAlgorithm.ToString() );
   Console::WriteLine( "Expect 100-continue = {0}", sp->Expect100Continue.ToString() );
   
}


void makeWebRequest( int hashCode, String^ Uri )
{
   HttpWebResponse^ res = nullptr;
   
   // 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 = dynamic_cast<HttpWebRequest^>(WebRequest::Create( Uri ));
      Console::WriteLine( "\nConnecting to {0} ............", Uri );
      
      // Get the response object.
      res = dynamic_cast<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: {0}", currentHashCode );
      Console::WriteLine( "New service point max idle time: {0}", currentServicePoint->MaxIdleTime );
      Console::WriteLine( "New service point is idle since {0}", 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 : {0}", e->Source );
      Console::WriteLine( "Message : {0}", e->Message );
   }
   finally
   {
      if ( res != nullptr )
            res->Close();
   }

}


// Show the user how to use this program when wrong inputs are entered.
void showUsage()
{
   Console::WriteLine( "Enter the proxy name as follows:" );
   Console::WriteLine( "\tcs_servicepoint proxyName" );
}


int main()
{
   array<String^>^args = Environment::GetCommandLineArgs();
   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 = gcnew Regex( "^[a-zA-Z]\\w{1,39}$" );
   if ( args->Length < 2 )
   {
      showUsage();
      return  -1;
   }

   String^ proxy = args[ 1 ];
   if ( (rex->Match(proxy))->Success != true )
   {
      Console::WriteLine( "Input string format not allowed." );
      return  -1;
   }

   String^ proxyAdd = String::Format( "http://{0}:{1}", proxy, port );
   
   // Create a proxy object.  
   WebProxy^ DefaultProxy = gcnew WebProxy( proxyAdd,true );
   
   // Set the proxy that all HttpWebRequest instances use.
   GlobalProxySelection::Select = DefaultProxy;
   
   // Get the base interface for proxy access for the 
   // WebRequest-based classes.
   IWebProxy^ Iproxy = GlobalProxySelection::Select;
   
   // 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.
   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 = gcnew 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: {0}", 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.
        GlobalProxySelection.set_Select(defaultProxy);

        // Get the base interface for proxy access for the 
        // WebRequest-based classes.
        IWebProxy iProxy = GlobalProxySelection.get_Select();

        // 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

System.Object
  System.Net.ServicePoint

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Windows 98, Windows Server 2000 SP4, Windows CE, Windows Millennium Edition, Windows Mobile for Pocket PC, Windows Mobile for Smartphone, Windows Server 2003, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP SP2, Windows XP Starter Edition

The Microsoft .NET Framework 3.0 is supported on Windows Vista, Microsoft Windows XP SP2, and Windows Server 2003 SP1.

.NET Framework

Supported in: 3.0, 2.0, 1.1, 1.0

.NET Compact Framework

Supported in: 2.0, 1.0

Community Additions

ADD
Show:
© 2014 Microsoft