使用 HTTP 连接到数据资源的应用程序用 ServicePoint 和 ServicePointManager 类来管理 Internet 连接
ServicePoint 类为应用程序提供一个终结点,应用程序可以连接到该终结点上来访问 Internet 资源。 ServicePoint 都由一个统一资源标识符 (URI) 标识,并且按照方案标识符(如http)和 URI 的宿主(如www.contoso.com)段进行分类,
例如,同一个 ServicePoint 实例可以提供对 http://www.contoso.com/index.htm 和 http://www.contoso.com/news.htm?date=today 两个 URI 的请求。
ServicePointManager :管理 ServicePoint 实例的创建和销毁的静态类。
创建一个 ServicePoint:程序请求的 Internet 资源不在现有 ServicePoint 实例集合中时。
ServicePoint 实例将被销毁:实例超过其最长空闲时间,或者当现有 ServicePoint 实例数超过应用程序的最大 ServicePoint 实例数时。
在 ServicePointManager 上设置 MaxServicePointIdleTime 和 MaxServicePoints 属性,可以控制 ServicePoint 实例的默认最长空闲时间和最大数目。默认: HttpWebRequest 类的应用程序最多使用两个与给定服务器的持久连接。
=====================
更改 ServicePointManager 类上的静态 DefaultConnectionLimit 属性,可以更改应用程序使用的连接数。不影响以前初始化的 ServicePoint 实例。
ServicePointManager.DefaultConnectionLimit = 4;//以后没组连接最多的默认连接数为4
但之后也可以通过ServicePoin.ConnectionLimit 在设置特定连接相关属性
Uri uri = new Uri("http://www.contoso.com/");
ServicePoint sp = ServicePointManager.FindServicePoint(uri);
sp.ConnectionLimit = 5;
连接分组
连接分组使单个应用程序中的特定请求与一个已定义的连接池相关联,这个连接池以WebRequest.ConnectionGroupName来区别。
为什么要用分组:假设有一个叫 Joe 的用户访问显示其工资信息的内部 Web 站点。对 Joe 进行身份验证后,中间层应用程序服务器使用 Joe 的凭据连接后端服务器以检索其工资信息。接着,Susan 也访问该站点并请求其工资信息。但由于中间层应用程序已使用 Joe 的凭据建立了连接,因此后端服务器以 Joe 的信息来响应。如果应用程序将每个对后端服务器的请求都分配到一个由用户名形成的连接组,则不会意外地与其他用户共享身份验证信息。
SHA1Managed Sha1 = new SHA1Managed();
Byte[] updHash = Sha1.ComputeHash(Encoding.UTF8.GetBytes(UserName + SecurelyStoredPassword + Domain));
String secureGroupName = Encoding.Default.GetString(updHash);
// Create a request for a specific URL.
WebRequest myWebRequest=WebRequest.Create("http://www.contoso.com");
myWebRequest.Credentials = new NetworkCredential(UserName, SecurelyStoredPassword, Domain);
myWebRequest.ConnectionGroupName = secureGroupName;//这条语句执行时将连接归组
WebResponse myWebResponse=myWebRequest.GetResponse();
// Insert the code that uses myWebResponse.
MyWebResponse.Close();
对后面的请求若分配给 UserName 变量不同的值,将会使用适当的凭据产生新的服务器连接