摘要:[FTP]測試FTP連線狀態
因為工作需要要測試FTP連線狀態
///
/// 測試連接狀態
///
///
///
///
///
private bool isValidConnection(string url, string user, string password)
{
FtpWebRequest request;
try
{
request = (FtpWebRequest)FtpWebRequest.Create(@"ftp://" + url);
request.Method = WebRequestMethods.Ftp.ListDirectory;
request.KeepAlive = true;
request.Credentials = new NetworkCredential(user, password);
request.GetResponse();
}
catch (WebException ex)
{
return false;
}
finally
{
request = null;
}
return true;
}
但是如果這樣連續測試2次 會發現第3次會逾時
後來搜了很久 雖然是同問題 看到以下這篇 感覺不清不楚
http://epaper.blueshop.com.tw/board/show.asp?subcde=BRD20130607204525V2R&fumcde=FUM20050124192253INM
.NET 預設對同個ServicePoint可以有兩個連線
要增加可以寫
1 | //設定單個ServicePoint的最大連線數 |
2 | ServicePointManager.DefaultConnectionLimit = 4; |
開新視窗(view plain) | 列印(print) | ? |
但是這樣還是會爆
因為連線連了並不會釋放
所以
1 | //連線前設定如果斷線了會釋放連線數 |
2 | request.KeepAlive = false; |
3 | //連線完設定回來 |
4 | request.KeepAlive = true; |
開新視窗(view plain) | 列印(print) | ? |
你可在程式debug中watch ServicePointManager 或是 request內有關connection的值
後來再去搜 發現
http://blog.xuite.net/tolarku/blog/32757529-VB.NET+concurrent+connect+%E9%99%90%E5%88%B6+2%E7%AD%86+-+webrequest
裡面的這一段
Dim iresponse As HttpWebResponse = irequest.GetResponse
MessageBox.Show(capture_url & "\n URL Exists.")
iresponse.close() '釋放已用完的 webresponse
後來想了一下 改入下面那2行
var response = request.GetResponse();
response.Close();
就解決了
///
/// 測試連接狀態
///
///
///
///
///
private bool isValidConnection(string url, string user, string password)
{
FtpWebRequest request;
try
{
request = (FtpWebRequest)FtpWebRequest.Create(@"ftp://" + url);
request.Method = WebRequestMethods.Ftp.ListDirectory;
request.KeepAlive = true;
request.Credentials = new NetworkCredential(user, password);
var response = request.GetResponse();
response.Close();
}
catch (WebException ex)
{
return false;
}
finally
{
request = null;
}
return true;
}
結論:恩 多學一個是一個
尾語:聽說正在做不符道德的事,多做好事可以心安!