Lire en anglais

Partager via


ServicePoint Classe

Définition

Fournit la gestion des connexions HTTP.

C#
public class ServicePoint
Héritage
ServicePoint

Exemples

L’exemple de code suivant crée un objet ServicePoint qui se connecte à l’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/");
        }
    }
}

Remarques

Attention

WebRequest, HttpWebRequest, ServicePointet WebClient sont obsolètes et vous ne devez pas les utiliser pour le nouveau développement. Utilisez HttpClient à la place.

La classe ServicePoint gère les connexions à une ressource Internet en fonction des informations d’hôte transmises dans l’URI (Uniform Resource Identifier) de la ressource. La connexion initiale à la ressource détermine les informations conservées par l’objet ServicePoint, qui sont ensuite partagées par toutes les demandes suivantes à cette ressource.

ServicePoint objets sont gérés par la classe ServicePointManager et sont créés, le cas échéant, par la méthode ServicePointManager.FindServicePoint. ServicePoint objets ne sont jamais créés directement, mais sont toujours créés et gérés par la classe ServicePointManager. Le nombre maximal d’objets ServicePoint qui peuvent être créés est défini par la propriété ServicePointManager.MaxServicePoints.

Chaque objet ServicePoint conserve sa connexion à une ressource Internet jusqu’à ce qu’il ait été inactif plus longtemps que le temps spécifié dans la propriété MaxIdleTime. Lorsqu’une ServicePoint dépasse la valeur de MaxIdleTime, elle peut être recyclée vers une autre connexion. La valeur par défaut de MaxIdleTime est définie par la propriété ServicePointManager.MaxServicePointIdleTime.

Lorsque la propriété ConnectionLeaseTimeout est définie sur une valeur autre que -1 et après l’expiration du délai spécifié, une connexion active ServicePoint est fermée après qu’elle services la requête suivante. Cela est utile pour les applications qui ne nécessitent pas de connexions actives ouvertes indéfiniment, car elles sont par défaut.

Note

Dans des conditions de charge élevée, certaines applications peuvent manquer de threads libres dans le ThreadPool, ce qui peut entraîner des performances système médiocres (par exemple, des temps de transaction élevés et variables).

Propriétés

Address

Obtient l’URI (Uniform Resource Identifier) du serveur auquel cet objet ServicePoint se connecte.

BindIPEndPointDelegate

Spécifie le délégué à associer un IPEndPoint local à un ServicePoint.

Certificate

Obtient le certificat reçu pour cet objet ServicePoint.

ClientCertificate

Obtient le dernier certificat client envoyé au serveur.

ConnectionLeaseTimeout

Obtient ou définit le nombre de millisecondes après quoi une connexion active ServicePoint est fermée.

ConnectionLimit

Obtient ou définit le nombre maximal de connexions autorisées sur cet objet ServicePoint.

ConnectionName

Obtient le nom de la connexion.

CurrentConnections

Obtient le nombre de connexions ouvertes associées à cet objet ServicePoint.

Expect100Continue

Obtient ou définit une valeur Boolean qui détermine si le comportement 100-Continuer est utilisé.

IdleSince

Obtient la date et l’heure auxquelles l’objet ServicePoint a été connecté pour la dernière fois à un hôte.

MaxIdleTime

Obtient ou définit la durée pendant laquelle une connexion associée à l’objet ServicePoint peut rester inactive avant la fermeture de la connexion.

ProtocolVersion

Obtient la version du protocole HTTP utilisé par l’objet ServicePoint.

ReceiveBufferSize

Obtient ou définit la taille de la mémoire tampon de réception pour le socket utilisé par cette ServicePoint.

SupportsPipelining

Indique si l’objet ServicePoint prend en charge les connexions pipeline.

UseNagleAlgorithm

Obtient ou définit une valeur Boolean qui détermine si l’algorithme Nagle est utilisé sur les connexions gérées par cet objet ServicePoint.

Méthodes

CloseConnectionGroup(String)

Supprime le groupe de connexions spécifié de cet objet ServicePoint.

Equals(Object)

Détermine si l’objet spécifié est égal à l’objet actuel.

(Hérité de Object)
GetHashCode()

Retourne une valeur de hachage pour une instance de ServicePoint.

GetHashCode()

Sert de fonction de hachage par défaut.

(Hérité de Object)
GetType()

Obtient la Type de l’instance actuelle.

(Hérité de Object)
MemberwiseClone()

Crée une copie superficielle du Objectactuel.

(Hérité de Object)
SetTcpKeepAlive(Boolean, Int32, Int32)

Active ou désactive l’option keep-alive sur une connexion TCP.

ToString()

Retourne une chaîne qui représente l’objet actuel.

(Hérité de Object)

S’applique à

Produit Versions
.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