Leer en inglés

Compartir a través de


ServicePoint Clase

Definición

Proporciona la administración de conexiones para las conexiones HTTP.

C#
public class ServicePoint
Herencia
ServicePoint

Ejemplos

En el ejemplo de código siguiente se crea un objeto ServicePoint que se conecta al URI www.contoso.com.

C#
// 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)
            {
                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/");
        }
    }
}

Comentarios

Precaución

WebRequest, HttpWebRequest, ServicePointy WebClient están obsoletos y no debe usarlos para el nuevo desarrollo. Use HttpClient en su lugar.

La clase ServicePoint controla las conexiones a un recurso de Internet en función de la información de host que se pasa en el identificador uniforme de recursos (URI) del recurso. La conexión inicial al recurso determina la información que mantiene el objeto ServicePoint, que luego comparte todas las solicitudes posteriores a ese recurso.

ServicePoint objetos se administran mediante la clase ServicePointManager y se crean, si es necesario, mediante el método ServicePointManager.FindServicePoint. ServicePoint los objetos nunca se crean directamente, pero siempre se crean y administran mediante la clase ServicePointManager. La propiedad ServicePointManager.MaxServicePoints establece el número máximo de objetos ServicePoint que se pueden crear.

Cada objeto ServicePoint mantiene su conexión a un recurso de Internet hasta que haya estado inactivo más tiempo que el tiempo especificado en la propiedad MaxIdleTime. Cuando un ServicePoint supera el valor de MaxIdleTime, se puede reciclar a otra conexión. El valor predeterminado de MaxIdleTime se establece mediante la propiedad ServicePointManager.MaxServicePointIdleTime.

Cuando la propiedad ConnectionLeaseTimeout se establece en un valor distinto de -1 y después de que transcurre el tiempo especificado, se cierra una conexión de ServicePoint activa después de que se aprotezca la siguiente solicitud. Esto es útil para las aplicaciones que no requieren conexiones activas que se abren indefinidamente, ya que son de forma predeterminada.

Nota

En condiciones de carga elevadas, algunas aplicaciones pueden agotarse de subprocesos libres en ThreadPool, lo que puede provocar un rendimiento deficiente del sistema (como tiempos de transacción altos y variables).

Propiedades

Address

Obtiene el identificador uniforme de recursos (URI) del servidor al que se conecta este objeto ServicePoint.

BindIPEndPointDelegate

Especifica el delegado para asociar un IPEndPoint local a un ServicePoint.

Certificate

Obtiene el certificado recibido para este objeto ServicePoint.

ClientCertificate

Obtiene el último certificado de cliente enviado al servidor.

ConnectionLeaseTimeout

Obtiene o establece el número de milisegundos después de los cuales se cierra una conexión de ServicePoint activa.

ConnectionLimit

Obtiene o establece el número máximo de conexiones permitidas en este objeto ServicePoint.

ConnectionName

Obtiene el nombre de la conexión.

CurrentConnections

Obtiene el número de conexiones abiertas asociadas a este objeto ServicePoint.

Expect100Continue

Obtiene o establece un valor de Boolean que determina si se usa el comportamiento 100-Continue.

IdleSince

Obtiene la fecha y hora en que el objeto ServicePoint se conectó por última vez a un host.

MaxIdleTime

Obtiene o establece la cantidad de tiempo que una conexión asociada al objeto ServicePoint puede permanecer inactiva antes de que se cierre la conexión.

ProtocolVersion

Obtiene la versión del protocolo HTTP que usa el objeto ServicePoint.

ReceiveBufferSize

Obtiene o establece el tamaño del búfer receptor para el socket usado por este ServicePoint.

SupportsPipelining

Indica si el objeto ServicePoint admite conexiones canalizaciones.

UseNagleAlgorithm

Obtiene o establece un valor de Boolean que determina si el algoritmo de Nagle se usa en las conexiones administradas por este objeto ServicePoint.

Métodos

CloseConnectionGroup(String)

Quita el grupo de conexiones especificado de este objeto ServicePoint.

Equals(Object)

Determina si el objeto especificado es igual al objeto actual.

(Heredado de Object)
GetHashCode()

Devuelve un valor hash para una instancia de ServicePoint.

GetHashCode()

Actúa como función hash predeterminada.

(Heredado de Object)
GetType()

Obtiene el Type de la instancia actual.

(Heredado de Object)
MemberwiseClone()

Crea una copia superficial del Objectactual.

(Heredado de Object)
SetTcpKeepAlive(Boolean, Int32, Int32)

Habilita o deshabilita la opción keep-alive en una conexión TCP.

ToString()

Devuelve una cadena que representa el objeto actual.

(Heredado de Object)

Se aplica a

Producto Versiones
.NET Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9, 10
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0, 2.1