ServicePoint 类

定义

为 HTTP 连接提供连接管理。

public class ServicePoint
继承
ServicePoint

示例

下面的代码示例创建一个连接到 URI www.contoso.comServicePoint 对象。

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

注解

注意

WebRequestHttpWebRequestServicePointWebClient 已过时,不应将其用于新开发。 请改用 HttpClient

ServicePoint 类基于在资源的统一资源标识符(URI)中传递的主机信息处理与 Internet 资源的连接。 与资源的初始连接确定 ServicePoint 对象维护的信息,然后由该资源的所有后续请求共享。

ServicePoint 对象由 ServicePointManager 类管理,并在必要时由 ServicePointManager.FindServicePoint 方法创建。 ServicePoint 对象永远不会直接创建,但始终由 ServicePointManager 类创建和管理。 ServicePointManager.MaxServicePoints 属性设置可以创建的最大 ServicePoint 对象数。

每个 ServicePoint 对象保持其与 Internet 资源的连接,直到其空闲时间超过 MaxIdleTime 属性中指定的时间。 当 ServicePoint 超过 MaxIdleTime 值时,可以将其回收到另一个连接。 MaxIdleTime 的默认值由 ServicePointManager.MaxServicePointIdleTime 属性设置。

ConnectionLeaseTimeout 属性设置为非 -1 的值,并在指定的时间过后关闭活动 ServicePoint 连接后,它将在服务下一个请求后关闭。 这对于不需要无限期打开的活动连接的应用程序非常有用,因为它们在默认情况下处于默认状态。

备注

在高负载条件下,某些应用程序可能会耗尽 ThreadPool 中的可用线程,这可能会导致系统性能不佳(如高事务时间和可变事务时间)。

属性

Address

获取此 ServicePoint 对象连接到的服务器统一资源标识符(URI)。

BindIPEndPointDelegate

指定要将本地 IPEndPointServicePoint关联的委托。

Certificate

获取为此 ServicePoint 对象收到的证书。

ClientCertificate

获取发送到服务器的最后一个客户端证书。

ConnectionLeaseTimeout

获取或设置活动 ServicePoint 连接关闭后的毫秒数。

ConnectionLimit

获取或设置此 ServicePoint 对象上允许的最大连接数。

ConnectionName

获取连接名称。

CurrentConnections

获取与此 ServicePoint 对象关联的打开连接数。

Expect100Continue

获取或设置一个 Boolean 值,该值确定是否使用 100-Continue 行为。

IdleSince

获取 ServicePoint 对象上次连接到主机的日期和时间。

MaxIdleTime

获取或设置与 ServicePoint 对象关联的连接在连接关闭之前可以保持空闲的时间量。

ProtocolVersion

获取 ServicePoint 对象使用的 HTTP 协议的版本。

ReceiveBufferSize

获取或设置此 ServicePoint使用的套接字的接收缓冲区的大小。

SupportsPipelining

指示 ServicePoint 对象是否支持管道连接。

UseNagleAlgorithm

获取或设置一个 Boolean 值,该值确定是否在此 ServicePoint 对象管理的连接上使用 Nagle 算法。

方法

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