Прочитать на английском

Поделиться через


ServicePoint Класс

Определение

Предоставляет управление подключениями для HTTP-подключений.

C#
public class ServicePoint
Наследование
ServicePoint

Примеры

В следующем примере кода создается объект ServicePoint, который подключается к www.contoso.comURI.

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

Комментарии

Внимание!

WebRequest, HttpWebRequest, ServicePointи WebClient устарели, и их не следует использовать для новой разработки. Вместо этого используйте HttpClient.

Класс ServicePoint обрабатывает подключения к интернет-ресурсу на основе сведений узла, передаваемых в универсальном коде ресурса ресурса (URI). Начальное подключение к ресурсу определяет сведения, которые поддерживает объект ServicePoint, который затем предоставляется всем последующим запросам этого ресурса.

ServicePoint объекты управляются классом ServicePointManager и создаются при необходимости методом ServicePointManager.FindServicePoint. ServicePoint объекты никогда не создаются напрямую, но всегда создаются и управляются классом ServicePointManager. Максимальное количество объектов ServicePoint, которые можно создать, устанавливается свойством ServicePointManager.MaxServicePoints.

Каждый объект ServicePoint поддерживает подключение к интернет-ресурсу до тех пор, пока он не будет неактивным, чем время, указанное в свойстве MaxIdleTime. Если ServicePoint превышает значение MaxIdleTime, его можно перезаработать в другое соединение. Значение по умолчанию MaxIdleTime задается свойством ServicePointManager.MaxServicePointIdleTime.

Если свойство ConnectionLeaseTimeout имеет значение, отличное от -1, и после истечения указанного времени, активное ServicePoint соединение закрывается после того, как он обслуживает следующий запрос. Это полезно для приложений, которые не требуют активных подключений, которые открываются неограниченное время, так как они по умолчанию.

Примечание

В условиях высокой нагрузки некоторые приложения могут выйти из свободных потоков в ThreadPool, что может привести к низкой производительности системы (например, высокой и переменной времени транзакций).

Свойства

Address

Возвращает универсальный код ресурса (URI) сервера, к которому подключается этот объект ServicePoint.

BindIPEndPointDelegate

Указывает делегат для связывания локального IPEndPoint с ServicePoint.

Certificate

Возвращает сертификат, полученный для этого объекта ServicePoint.

ClientCertificate

Возвращает последний сертификат клиента, отправленный серверу.

ConnectionLeaseTimeout

Возвращает или задает количество миллисекунда, после которого закрывается активное ServicePoint подключение.

ConnectionLimit

Возвращает или задает максимальное количество подключений, разрешенных для этого объекта ServicePoint.

ConnectionName

Возвращает имя подключения.

CurrentConnections

Возвращает количество открытых подключений, связанных с этим объектом ServicePoint.

Expect100Continue

Возвращает или задает значение Boolean, определяющее, используется ли поведение 100-Continue.

IdleSince

Возвращает дату и время последнего подключения объекта ServicePoint к узлу.

MaxIdleTime

Возвращает или задает время, когда соединение, связанное с объектом ServicePoint, может оставаться бездействием до закрытия подключения.

ProtocolVersion

Возвращает версию протокола HTTP, используемого объектом ServicePoint.

ReceiveBufferSize

Возвращает или задает размер принимающего буфера для сокета, используемого этим ServicePoint.

SupportsPipelining

Указывает, поддерживает ли объект ServicePoint конвейерные подключения.

UseNagleAlgorithm

Возвращает или задает значение Boolean, определяющее, используется ли алгоритм Nagle для подключений, управляемых этим объектом ServicePoint.

Методы

CloseConnectionGroup(String)

Удаляет указанную группу подключений из этого объекта ServicePoint.

Equals(Object)

Определяет, равен ли указанный объект текущему объекту.

(Унаследовано от Object)
GetHashCode()

Возвращает хэш-значение для экземпляра ServicePoint.

GetHashCode()

Служит хэш-функцией по умолчанию.

(Унаследовано от Object)
GetType()

Возвращает Type текущего экземпляра.

(Унаследовано от Object)
MemberwiseClone()

Создает неглубокую копию текущей Object.

(Унаследовано от Object)
SetTcpKeepAlive(Boolean, Int32, Int32)

Включает или отключает параметр поддержания активности в TCP-подключении.

ToString()

Возвращает строку, представляющую текущий объект.

(Унаследовано от Object)

Применяется к

Продукт Версии
.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