Export (0) Print
Expand All

ServicePoint Class

Provides connection management for HTTP connections.

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

'Declaration
Public Class ServicePoint
'Usage
Dim instance As ServicePoint

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 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).   
' Reusing service points in this way can help improve application  performance. 

Imports System
Imports System.Net
Imports System.Threading
Imports System.Text.RegularExpressions

Namespace Mssc.Services.ConnectionManagement
    Module M_TestServicePoint

        Class TestServicePoint
            Private Shared Sub ShowProperties(ByVal sp As ServicePoint)

                Console.WriteLine("Done calling FindServicePoint")

                ' Display the ServicePoint Internet resource address.
                Console.WriteLine(("Address = " + 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.ToString()))

                Console.WriteLine(("ConnectionName = " + sp.ConnectionName))

                ' Display the maximum number of connections allowed on this  
                ' ServicePoint instance.
                Console.WriteLine(("ConnectionLimit = " + sp.ConnectionLimit.ToString()))

                ' Display the number of connections associated with this  
                ' ServicePoint instance.
                Console.WriteLine(("CurrentConnections = " + sp.CurrentConnections.ToString()))

                If sp.Certificate Is Nothing Then
                    Console.WriteLine("Certificate = (null)")
                Else
                    Console.WriteLine(("Certificate = " + sp.Certificate.ToString()))
                End If 

                If sp.ClientCertificate Is Nothing Then
                    Console.WriteLine("ClientCertificate = (null)")
                Else
                    Console.WriteLine(("ClientCertificate = " + sp.ClientCertificate.ToString()))
                End If

                Console.WriteLine("ProtocolVersion = " + sp.ProtocolVersion.ToString())
                Console.WriteLine(("SupportsPipelining = " + sp.SupportsPipelining.ToString()))


                Console.WriteLine("UseNagleAlgorithm = " + sp.UseNagleAlgorithm.ToString())
                Console.WriteLine("Expect 100-continue = " + sp.Expect100Continue.ToString())
            End Sub 'ShowProperties





            Private Shared Sub makeWebRequest(ByVal hashCode As Integer, ByVal Uri As String)
                Dim res As HttpWebResponse = Nothing 

                ' 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. 
                    Dim req As HttpWebRequest = CType(WebRequest.Create(Uri), HttpWebRequest)
                    Console.WriteLine((ControlChars.Lf + "Connecting to " + Uri + " ............"))

                    ' Get the response object.
                    res = CType(req.GetResponse(), HttpWebResponse)
                    Console.WriteLine("Connected." + ControlChars.Lf)
                    Dim currentServicePoint As ServicePoint = req.ServicePoint

                    ' Display new service point properties. 
                    Dim currentHashCode As Integer = currentServicePoint.GetHashCode()
                    Console.WriteLine(("New service point hashcode: " + currentHashCode.ToString()))
                    Console.WriteLine(("New service point max idle time: " + currentServicePoint.MaxIdleTime.ToString()))
                    Console.WriteLine(("New service point is idle since " + currentServicePoint.IdleSince.ToString()))

                    ' Check that a new ServicePoint instance has been created. 
                    If hashCode = currentHashCode Then
                        Console.WriteLine("Service point reused.")
                    Else
                        Console.WriteLine("A new service point created.")
                    End If 
                Catch e As Exception
                    Console.WriteLine(("Source : " + e.Source))
                    Console.WriteLine(("Message : " + e.Message))
                Finally 
                    If Not (res Is Nothing) Then
                        res.Close()
                    End If 
                End Try 
            End Sub 'makeWebRequest


            ' Show the user how to use this program when wrong inputs are entered. 
            Private Shared Sub showUsage()
                Console.WriteLine("Enter the proxy name as follows:")
                Console.WriteLine(ControlChars.Tab + "vb_servicepoint proxyName")
            End Sub 'showusage

            ' This is the program entry point. It allows the user to enter  
            ' a server name that is used to locate its current homepage. 
            Public Shared Sub Main(ByVal args() As String)
                Dim proxy As String = Nothing 
                Dim port As Integer = 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. 
                Dim rex As New Regex("^[a-zA-Z]\w{1,39}$")

                If args.Length = 0 Then 
                    ' Show how to use this program.
                    showUsage()
                    Return 
                End If

                proxy = args(0)
                If (Not (rex.Match(proxy)).Success) Then
                    Console.WriteLine("Input string format not allowed.")
                    Return 
                End If 

                ' Create a proxy object.   
                Dim proxyAdd As String
                proxyAdd = "http://" + proxy + ":" + port.ToString()


                Dim DefaultProxy As 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. 
                Dim Iproxy As IWebProxy = WebRequest.DefaultWebProxy

                ' Set the maximum number of ServicePoint instances to maintain. 
                ' Note that, 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. 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. 
                Dim MS As New Uri("http://msdn.microsoft.com/")

                ' Use the FindServicePoint method to find an existing  
                ' ServicePoint object or to create a new one.    
                Dim servicePoint As ServicePoint = ServicePointManager.FindServicePoint(MS, Iproxy)
                ShowProperties(servicePoint)
                Dim hashCode As Integer = servicePoint.GetHashCode()
                Console.WriteLine(("Service point hashcode: " + hashCode.ToString()))

                ' 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/")

            End Sub 'Main


        End Class 'TestServicePoint

    End Module 
End Namespace
// 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 <mscorlib.dll>
#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(S"Done calling FindServicePoint()...");

    // Display the ServicePoint Internet resource address.
    Console::WriteLine(S"Address = {0}", sp->Address);

    // Display the date and time that the ServicePoint was last 
    // connected to a host.
    Console::WriteLine(S"IdleSince = {0}", __box(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(S"MaxIdleTime = {0}", __box(sp->MaxIdleTime));

    Console::WriteLine(S"ConnectionName = {0}", sp->ConnectionName);

    // Display the maximum number of connections allowed on this 
    // ServicePoint instance.
    Console::WriteLine(S"ConnectionLimit = {0}", __box(sp->ConnectionLimit));

    // Display the number of connections associated with this 
    // ServicePoint instance.
    Console::WriteLine(S"CurrentConnections = {0}", __box(sp->CurrentConnections));        

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

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

    Console::WriteLine(S"ProtocolVersion = {0}", sp->ProtocolVersion->ToString());
    Console::WriteLine(S"SupportsPipelining = {0}", __box(sp->SupportsPipelining));

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

void makeWebRequest(int hashCode, String* Uri)
{
    HttpWebResponse* res = 0;

    // Make sure that the idle time has elapsed, so that a new 
    // ServicePoint instance is created.
    Console::WriteLine(S"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(S"\nConnecting to {0} ............", Uri);

        // Get the response object.
        res = dynamic_cast<HttpWebResponse*>(req->GetResponse());
        Console::WriteLine(S"Connected.\n");
        ServicePoint* currentServicePoint = req->ServicePoint;

        // Display new service point properties.
        int currentHashCode = currentServicePoint->GetHashCode();
        Console::WriteLine(S"New service point hashcode: {0}", __box(currentHashCode));
        Console::WriteLine(S"New service point max idle time: {0}", __box(currentServicePoint->MaxIdleTime));
        Console::WriteLine(S"New service point is idle since {0}", __box(currentServicePoint->IdleSince));

        // Check that a new ServicePoint instance has been created.
        if (hashCode == currentHashCode)
            Console::WriteLine(S"Service point reused.");
        else
            Console::WriteLine(S"A new service point created.");
    }
    catch(Exception* e)
    {
        Console::WriteLine(S"Source : {0}", e->Source);
        Console::WriteLine(S"Message : {0}", e->Message);
    }
    __finally
    {
        if (res != 0)
            res->Close();
    }
}

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

int main() 
{
    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 = new Regex(S"^[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(S"Input string format not allowed.");
        return -1;
    }
    String* proxyAdd = String::Format( S"http://{0}:{1}", proxy, __box(port));
    // Create a proxy object.  
    WebProxy* DefaultProxy = new 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 = 1000;


    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(S"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(S"Service point hashcode: {0}", __box(hashCode));

    // Make a request with the same scheme identifier and host fragment
    // used to create the previous ServicePoint object.
    makeWebRequest(hashCode, S"http://msdn.microsoft.com/library/");
}

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 7, Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2008 R2, Windows Server 2008, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98, Windows CE, Windows Mobile for Smartphone, Windows Mobile for Pocket PC

The .NET Framework and .NET Compact Framework do not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

.NET Framework

Supported in: 3.5, 3.0, 2.0, 1.1, 1.0

.NET Compact Framework

Supported in: 3.5, 2.0, 1.0

Community Additions

ADD
Show:
© 2014 Microsoft