日期:2014-05-18 浏览次数:21084 次
public void Connect(string server, int port, Proxy proxy, ConnectCallBack callback)
{
    this._client = new TcpClient();
    try
    {
        this._server = server;
        this._port = port;
        this._callback = callback;
        this._proxy = proxy;
        this._client.BeginConnect(proxy.Server, proxy.Port, new AsyncCallback(this.Connected), null);
    }
    catch
    {
    }
}
private void Connected(IAsyncResult ar)
{
    try
    {
        this._client.EndConnect(ar);
        NetworkStream stream = this._client.GetStream();
        StreamWriter writer = new StreamWriter(stream);
        writer.WriteLine(string.Format("CONNECT {0}:{1} HTTP/1.1", this._proxy.Server, this._proxy.Port));
        writer.WriteLine("Accept: */*");
        writer.WriteLine("Content-Type: text/html");
        writer.WriteLine("Proxy-Connection: Keep-Alive");
        if (!string.IsNullOrEmpty(this._proxy.User))
        {
            string s = this._proxy.User + ":" + this._proxy.Password;
            writer.WriteLine("Proxy-Authorization: Basic " + Convert.ToBase64String(Encoding.ASCII.GetBytes(s)));
        }
        writer.WriteLine("Content-length: 0");
        writer.WriteLine();
        writer.Flush();
        bool isSuccess = false;
        string msg = "代理服务器错误";
        StreamReader reader = new StreamReader(stream);
        for (string str4 = reader.ReadLine(); (str4 != null) && (str4.Length > 0); str4 = reader.ReadLine())
        {
            if (str4.ToUpper().IndexOf("HTTP/1.0") > -1)
            {
                string[] strArray = str4.Split(new char[] { ' ' });
                if (strArray.Length > 1)
                {
                    if (strArray[1] == "200")
                    {
                        isSuccess = true;
                        msg = "代理服务器工作正常";
                    }
                    else
                    {
                        msg = "代理服务器错误 错误码" + strArray[1];
                    }
                }
            }
        }
        this._callback(isSuccess, msg);
    }
    catch (Exception)
    {
        this._callback(false, "连接代理服务器失败");
    }
}