Sil*_*ght 2 c# proxy .net-4.0 windows-applications
我有一个很大的代理服务器列表(txt文件,格式= ip:每行的端口),并编写下面的代码来检查它们:
public static void MyChecker()
{
string[] lines = File.ReadAllLines(txtProxyListPath.Text);
List<string> list_lines = new List<string>(lines);
List<string> list_lines_RemovedDup = new List<string>();
HashSet<string> HS = new HashSet<string>();
int Duplicate_Count = 0;
int badProxy = 0;
int CheckedCount = 0;
foreach (string line in list_lines)
{
string[] line_char = line.Split(':');
string ip = line_char[0];
string port = line_char[1];
if (CanPing(ip))
{
if (SoketConnect(ip, port))
{
if (CheckProxy(ip, port))
{
string ipAndport = ip + ":" + port;
if (HS.Add(ipAndport))
{
list_lines_RemovedDup.Add(ipAndport);
CheckedCount++;
}
else
{
Duplicate_Count++;
CheckedCount++;
}
}
else
{
badProxy++;
CheckedCount++;
}
}
else
{
badProxy++;
CheckedCount++;
}
}
else
{
badProxy++;
CheckedCount++;
}
}
public static bool CanPing(string ip)
{
Ping ping = new Ping();
try
{
PingReply reply = ping.Send(ip, 2000);
if (reply == null)
return false;
return (reply.Status == IPStatus.Success);
}
catch (PingException Ex)
{
return false;
}
}
public static bool SoketConnect(string ip, string port)
{
var is_success = false;
try
{
var connsock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
connsock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, 200);
System.Threading.Thread.Sleep(500);
var hip = IPAddress.Parse(ip);
var ipep = new IPEndPoint(hip, int.Parse(port));
connsock.Connect(ipep);
if (connsock.Connected)
{
is_success = true;
}
connsock.Close();
}
catch (Exception)
{
is_success = false;
}
return is_success;
}
public static bool CheckProxy(string ip, string port)
{
try
{
WebClient WC = new WebClient();
WC.Proxy = new WebProxy(ip, int.Parse(port));
WC.DownloadString("http://SpecificWebSite.com");
return true;
}
catch (Exception)
{
return false;
}
}
Run Code Online (Sandbox Code Playgroud)
但我认为我应该重写这些代码,因为它们非常慢.
我在这行不好延迟:
WC.DownloadString("http://SpecificWebSite.com");
和
PingReply reply = ping.Send(ip, 2000);
,这是不好的大名单.
我是在正确的方向上编写这些代码还是应该更改它们(哪些部分)?
我该如何优化它们?
提前致谢
你可以改进很多东西.
仅这些就可以加快你的过程速度.
根据要求,这是一个如何使用HttpWebRequests的示例
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Proxy = null; // set proxy here
request.Timeout = 10000;
request.Method = "HEAD";
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
Console.WriteLine(response.StatusCode);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3566 次 |
| 最近记录: |