Exemple #1
0
        public void UpdateServer(ReqState state, IPAddress ip)
        {
            var server = Servers.Where((s) => s.Address == ip && s.Port == state.Port).FirstOrDefault();

            if (server == null)
            {
                server = new GameServer()
                {
                    Address          = ip,
                    ConnectedPlayers = state.ConnectedPlayers,
                    InLobby          = state.InLobby,
                    LastData         = DateTime.Now,
                    Port             = state.Port,
                    TotalPlayers     = state.TotalPlayers,
                    Version          = state.ServerVersion,
                    GameMode         = state.GameMode,
                };
                Servers.Add(server);
            }
            else
            {
                server.ConnectedPlayers = state.ConnectedPlayers;
                server.InLobby          = state.InLobby;
                server.TotalPlayers     = state.TotalPlayers;
                server.LastData         = DateTime.Now;
                server.Version          = state.ServerVersion;
            }
        }
Exemple #2
0
        private void bw_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                byte[] buf = System.Text.Encoding.ASCII.GetBytes(String.Format("GET {0}{1} HTTP/1.1{3}Host: {2}{3}{3}{3}", Subsite, ( random ? new Functions().RandomString() : null ), Host, Environment.NewLine));
                IPEndPoint RHost = new IPEndPoint(System.Net.IPAddress.Parse(IP), Port);
                while (IsFlooding)
                {
                    State = ReqState.Ready; // SET STATE TO READY //
                    LastAction = Tick();
                    byte[] recvBuf = new byte[64];
                    Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                    State = ReqState.Connecting; // SET STATE TO CONNECTING //

                    try { socket.Connect(RHost); }
                    catch { continue; }

                    socket.Blocking = Resp;
                    State = ReqState.Requesting; // SET STATE TO REQUESTING //
                    socket.Send(buf, SocketFlags.None);
                    State = ReqState.Downloading; Requested++; // SET STATE TO DOWNLOADING // REQUESTED++
                    if (Resp) socket.Receive(recvBuf, 64, SocketFlags.None);
                    State = ReqState.Completed; Downloaded++; // SET STATE TO COMPLETED // DOWNLOADED++
                    tTimepoll.Stop();
                    tTimepoll.Start();
                    if (Delay >= 0) System.Threading.Thread.Sleep(Delay+1);
                }
            }
            catch { }
            finally { IsFlooding = false; }
        }
Exemple #3
0
        private void wrExThrow(string msg, string trace)
        {
            string exMessage = msg;

            sResponse = "<WebReq_Error>" + msg + "</WebReq_Error>";
            //if (Filename != "")
            //{
            //    FileStream fs = new FileStream(Filename, FileMode.Create);
            //    fs.Write(System.Text.Encoding.ASCII.GetBytes(Response), 0, Response.Length);
            //    fs.Flush(); fs.Close(); fs.Dispose();
            //}
            if (trace.Contains(":line "))
            {
                trace = trace.Substring(trace.IndexOf(":line ") + 6);
            }
            else
            {
                trace = "";
            }
            if (trace != "")
            {
                exMessage += "\r\nSTACK TRACING --> " + trace;
            }
            wrErrlog(exMessage); socket.Close();
            State = ReqState.Failed; Progress = 0; isReady = true;
        }
Exemple #4
0
        public void Request(Uri Url, WebHeaderCollection cHeaders, byte[] baPostdata, string sMPBound, int iPostType,
                            string sFilename, bool bReturnStr)
        {
            sResponseCode = ""; msResponse = new MemoryStream();
            URI           = Url; Filename = sFilename; ReturnStr = bReturnStr;
            isReady       = false; State = ReqState.Connecting;
            Headers       = new WebHeaderCollection();
            outHeaders.Add("Host: " + URI.Host);
            outHeaders.Add("Connection: " + "Close");
            outHeaders.Add("User-Agent: pImgDB/" + cb.sAppVer + " (Windows NT 5.1; U; en)");

            for (int a = 0; a < cHeaders.Count; a++)
            {
                outHeaders.Add(cHeaders.GetKey(a) + ": " + cHeaders.Get(a));
            }
            ConMode = iPostType;
            if (ConMode != 1)
            {
                ConQHdr = "POST"; Postdata = baPostdata;
                outHeaders.Add("Content-Length: " + Postdata.Length);
                if (ConMode == 3)
                {
                    MPBound = sMPBound;
                    ConPHdr = "multipart/form-data; boundary=" + MPBound;
                }
                outHeaders.Add("Content-Type: " + ConPHdr);
            }

            BackgroundWorker bw = new BackgroundWorker();

            bw.DoWork += new DoWorkEventHandler(bw_DoWork);
            bw.RunWorkerAsync();
        }
Exemple #5
0
 private void bw_DoWork(object sender, DoWorkEventArgs e)
 {
     try
     {
         byte[] buf = System.Text.Encoding.ASCII.GetBytes(
             "GET " + Subsite + " HTTP/1.0\r\n\r\n\r\n");
         IPEndPoint RHost = new IPEndPoint(System.Net.IPAddress.Parse(IP), Port);
         while (isFlooding)
         {
             State      = ReqState.Ready; // SET STATE TO READY //
             LastAction = Tick();
             byte[] recvBuf = new byte[64];
             Socket sck     = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
             State = ReqState.Connecting; // SET STATE TO CONNECTING //
             sck.Connect(RHost);
             sck.Blocking = Resp;
             State        = ReqState.Requesting;         // SET STATE TO REQUESTING //
             sck.Send(buf, SocketFlags.None);
             State = ReqState.Downloading; iRequested++; // SET STATE TO DOWNLOADING // REQUESTED++
             if (Resp)
             {
                 sck.Receive(recvBuf, 64, SocketFlags.None);
             }
             State = ReqState.Completed; iDownloaded++; // SET STATE TO COMPLETED // DOWNLOADED++
             if (Delay > 0)
             {
                 System.Threading.Thread.Sleep(Delay);
             }
         }
     }
     catch { }
     isFlooding = false;
 }
Exemple #6
0
 void tTimepoll_Tick(object sender, EventArgs e)
 {
     if (Tick() > LastAction + Timeout)
     {
         isFlooding = false; iFailed++; State = ReqState.Failed;
     }
 }
 void RecieveCallBack(IAsyncResult iaRes)
 {
     try
     {
         ReqState     state      = (ReqState)iaRes.AsyncState;
         WebResponse  response   = state.Request.EndGetResponse(iaRes);
         Stream       s          = (Stream)response.GetResponseStream();
         StreamReader sr         = new StreamReader(s);
         string       strRes     = sr.ReadToEnd();
         Hashtable    saveData   = (Hashtable)JSON.JsonDecode(strRes);
         string[]     saveValues = ((string)saveData["value"]).Split('@');
         selectedPrefecture = saveValues[0];
         selectedSystemId   = saveValues[1];
         selectedSystemName = saveValues[2];
         response.Close();
         s.Close();
         sr.Close();
         SaveDataRecieved(GetDataState.Success);
     }
     catch (Exception ex)
     {
         AddErrorLog(ex);
         retryCnt--;
         if (retryCnt > -1)
         {
             GetSaveData(((ReqState)iaRes.AsyncState).UserId);
         }
         else
         {
             retryCnt = 3;
             SaveDataRecieved(GetDataState.Error);
         }
         //SaveDataRecieved(GetDataState.Error);
     }
 }
		void tTimepoll_Tick(object sender, EventArgs e)
		{
			if(Tick() > LastAction + Timeout)
			{
				Failed++; State = ReqState.Failed;
				tTimepoll.Stop();
				if(IsFlooding)
					tTimepoll.Start();
			}
		}
        public void GetSaveData(string userId)
        {
            WebRequest req   = WebRequest.Create("http://libron.net/api/storage?key=" + userId);
            ReqState   state = new ReqState()
            {
                Request = req, UserId = userId
            };
            IAsyncResult iares = req.BeginGetResponse(new AsyncCallback(RecieveCallBack), state);

            ThreadPool.RegisterWaitForSingleObject(iares.AsyncWaitHandle, new WaitOrTimerCallback(TimeoutCallback), req, 2000, true);
        }
Exemple #10
0
    public void ChangeStatus(int id, ReqState status)
    {
        string connectionURL = MakeConnectionURL();

        this.conn = new MySqlConnection(connectionURL);
        this.conn.Open();
        string          sql = "UPDATE requests SET status=" + (int)status + " WHERE Id=" + id;
        MySqlCommand    cmd = new MySqlCommand(sql, conn);
        MySqlDataReader rdr = cmd.ExecuteReader();

        rdr.Close();
    }
Exemple #11
0
 void tTimepoll_Tick(object sender, EventArgs e)
 {
     if (Tick() > LastAction + Timeout)
     {
         Failed++; State = ReqState.Failed;
         tTimepoll.Stop();
         if (IsFlooding)
         {
             tTimepoll.Start();
         }
     }
 }
Exemple #12
0
        public void Request(Uri Url, string sFilename, bool bReturnStr)
        {
            isReady               = false; State = ReqState.Connecting;
            URI                   = Url; Filename = sFilename; ReturnStr = bReturnStr;
            Headers               = new WebHeaderCollection();
            Headers["Host"]       = URI.Host;
            Headers["Keep-Alive"] = "close";

            BackgroundWorker bw = new BackgroundWorker();

            bw.DoWork += new DoWorkEventHandler(bw_DoWork);
            bw.RunWorkerAsync();
        }
Exemple #13
0
        private void bw_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                while (IsFlooding)
                {
                    string theSubsite = BuildRandomSubsite();
                    string format     =
                        String.Format("GET {0}{1} HTTP/1.1{5}Host: {3}{5}User-Agent: {2}{5}Accept: */*{5}{4}{5}{5}", theSubsite,
                                      (AllowRandom ? Functions.RandomString() : null), Functions.RandomUserAgent(), Host,
                                      (AllowGzip ? "Accept-Encoding: gzip, deflate" + Environment.NewLine : null),
                                      Environment.NewLine);

                    byte[]     buf   = System.Text.Encoding.ASCII.GetBytes(String.Format("GET {0}{1} HTTP/1.1{5}Host: {3}{5}User-Agent: {2}{5}Accept: */*{5}{4}{5}{5}", theSubsite, (AllowRandom ? Functions.RandomString() : null), Functions.RandomUserAgent(), Host, (AllowGzip ? "Accept-Encoding: gzip, deflate" + Environment.NewLine : null), Environment.NewLine));
                    IPEndPoint RHost = new IPEndPoint(System.Net.IPAddress.Parse(IP), Port);

                    State      = ReqState.Ready; // SET STATE TO READY //
                    LastAction = Tick();
                    byte[] recvBuf = new byte[64];
                    Socket socket  = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                    State = ReqState.Connecting; // SET STATE TO CONNECTING //

                    try { socket.Connect(RHost); }
                    catch { continue; }

                    socket.Blocking = Resp;
                    State           = ReqState.Requesting;     // SET STATE TO REQUESTING //
                    socket.Send(buf, SocketFlags.None);
                    State = ReqState.Downloading; Requested++; // SET STATE TO DOWNLOADING // REQUESTED++

                    if (Resp)
                    {
                        socket.Receive(recvBuf, 64, SocketFlags.None);
                    }

                    State = ReqState.Completed; Downloaded++; // SET STATE TO COMPLETED // DOWNLOADED++
                    tTimepoll.Stop();
                    tTimepoll.Start();

                    if (Delay >= 0)
                    {
                        System.Threading.Thread.Sleep(Delay + 1);
                    }
                }
            }
            catch { }
            finally { IsFlooding = false; }
        }
Exemple #14
0
        private void bw_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                IPEndPoint RHost = new IPEndPoint(IPAddress.Parse(IP), Port);
                while (this.IsFlooding)
                {
                    State      = ReqState.Ready;                // SET STATE TO READY //
                    lastAction = Tick();
                    byte[] recvBuf = new byte[128];
                    using (Socket socket = new Socket(RHost.AddressFamily, SocketType.Stream, ProtocolType.Tcp))
                    {
                        socket.NoDelay = true;
                        State          = ReqState.Connecting;                // SET STATE TO CONNECTING //

                        try { socket.Connect(RHost); }
                        catch (SocketException) { goto _continue; }

                        byte[] buf = Encoding.ASCII.GetBytes(String.Format("GET {0}{1} HTTP/1.1{5}Host: {3}{5}User-Agent: {2}{5}Accept: */*{5}{4}{5}{5}", Subsite, (AllowRandom ? Functions.RandomString() : ""), Functions.RandomUserAgent(), Host, (AllowGzip ? "Accept-Encoding: gzip, deflate" + Environment.NewLine : ""), Environment.NewLine));

                        socket.Blocking = Resp;
                        State           = ReqState.Requesting;               // SET STATE TO REQUESTING //

                        try { socket.Send(buf, SocketFlags.None); }
                        catch (SocketException) { goto _continue; }

                        State = ReqState.Downloading; Requested++;                         // SET STATE TO DOWNLOADING // REQUESTED++

                        if (Resp)
                        {
                            socket.Receive(recvBuf, recvBuf.Length, SocketFlags.None);
                        }
                    }
                    State = ReqState.Completed; Downloaded++;                     // SET STATE TO COMPLETED // DOWNLOADED++
                    tTimepoll.Stop();
                    tTimepoll.Start();
_continue:
                    if (Delay >= 0)
                    {
                        System.Threading.Thread.Sleep(Delay + 1);
                    }
                }
            }
            // Analysis disable once EmptyGeneralCatchClause
            catch { }
            finally { tTimepoll.Stop(); State = ReqState.Ready; this.IsFlooding = false; }
        }
Exemple #15
0
    public object[] GetRequestsByStatus(ReqState status)
    {
        ArrayList requests = new ArrayList();

        string connectionURL = MakeConnectionURL();

        this.conn = new MySqlConnection(connectionURL);
        this.conn.Open();

        string          sql = "SELECT * FROM requests WHERE Status=" + (int)status;
        MySqlCommand    cmd = new MySqlCommand(sql, conn);
        MySqlDataReader rdr = cmd.ExecuteReader();

        while (rdr.Read())
        {
            requests.Add(rdr["Id"]);
        }
        return(requests.ToArray());
    }
Exemple #16
0
        void tTimepoll_Tick(object sender, EventArgs e)
        {
            if (intShowStats)
            {
                return;
            }
            intShowStats = true;

            if (Tick() > lastAction + Timeout)
            {
                Failed++; State = ReqState.Failed;
                tTimepoll.Stop();
                if (this.IsFlooding)
                {
                    tTimepoll.Start();
                }
            }

            intShowStats = false;
        }
Exemple #17
0
        public void Request(Uri Url, WebHeaderCollection cHeaders, string sPostdata, string sFilename, bool bReturnStr)
        {
            isReady                  = false; State = ReqState.Connecting;
            URI                      = Url; Filename = sFilename; ReturnStr = bReturnStr;
            Headers                  = new WebHeaderCollection();
            outHeaders["Host"]       = URI.Host;
            outHeaders["Keep-Alive"] = "close";
            for (int a = 0; a < cHeaders.Count; a++)
            {
                outHeaders.Add(cHeaders.GetKey(a) + ": " + cHeaders.Get(a));
            }
            if (sPostdata != "")
            {
                ConMode = "POST"; Postdata = sPostdata;
                outHeaders.Add("Content-Length: " + Postdata.Length);
            }

            BackgroundWorker bw = new BackgroundWorker();

            bw.DoWork += new DoWorkEventHandler(bw_DoWork);
            bw.RunWorkerAsync();
        }
Exemple #18
0
        private void bw_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                IPEndPoint RHost = new IPEndPoint(Dns.GetHostEntry(URI.Host).AddressList[0], URI.Port);
                State = ReqState.Connecting; socket.Connect(RHost); State = ReqState.Requesting;
                string ReqStr = "GET " + URI.PathAndQuery + " HTTP/1.0\r\n" + Headers;
                socket.Send(System.Text.Encoding.ASCII.GetBytes(ReqStr));
                ParseHeader();

                string tFName = "";
                do
                {
                    tFName = "Chanmongler_" + RandomChars(6) + ".tmp";
                }while (File.Exists(tFName));
                FileStream   streamOut = File.Open(tFName, FileMode.Create, FileAccess.Write, FileShare.ReadWrite);
                BinaryWriter writer = new BinaryWriter(streamOut);
                byte[]       RecvBuffer = new byte[cSize]; int nBytes, nTotalBytes = 0;
                while ((nBytes = socket.Receive(RecvBuffer, 0, cSize, SocketFlags.None)) > 0)
                {
                    nTotalBytes += nBytes; State = ReqState.Downloading;
                    Progress     = Math.Round(((double)100 - ((double)cLength - (double)nTotalBytes) * (double)100 / (double)cLength), 1);
                    writer.Write(RecvBuffer, 0, nBytes);
                    if (ReturnStr)
                    {
                        Response += Encoding.ASCII.GetString(RecvBuffer, 0, nBytes);
                    }
                }
                writer.Close(); streamOut.Close(); socket.Close();
                if (Filename != "")
                {
                    File.Move(tFName, Filename);
                }
            }
            catch { }
            State   = ReqState.Completed; Progress = 100;
            isReady = true;
        }
Exemple #19
0
 public void GetSaveData(string userId)
 {
     WebRequest req = WebRequest.Create("http://libron.net/api/storage?key=" + userId);
     ReqState state = new ReqState() { Request = req, UserId = userId };
     IAsyncResult iares = req.BeginGetResponse(new AsyncCallback(RecieveCallBack), state);
     ThreadPool.RegisterWaitForSingleObject(iares.AsyncWaitHandle, new WaitOrTimerCallback(TimeoutCallback), req, 2000, true);
 }
Exemple #20
0
        private void bw_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                // ~~~ Create socket, set timeout ~~~ \\
                socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                IPEndPoint RHost = new IPEndPoint(Dns.GetHostEntry(URI.Host).AddressList[0], URI.Port);
                if (iTimeout != -1)
                {
                    socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, iTimeout);
                    socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, iTimeout);
                    BackgroundWorker bwTimeout = new BackgroundWorker();
                    bwTimeout.DoWork += new DoWorkEventHandler(bwTimeout_DoWork);
                    bwTimeout.RunWorkerAsync();
                }

                // ~~~ Create request, send request ~~~ \\
                State = ReqState.Connecting;
                try
                {
                    socket.Connect(RHost);
                }
                catch
                {
                    throw new Exception("#02-0002");
                }
                State = ReqState.Requesting;
                string ReqStr = ConQHdr + " " + URI.PathAndQuery + " HTTP/1.1\r\n" + outHeaders;
                //Response = ReqStr; isReady = true; return;
                byte[] bPck = System.Text.Encoding.ASCII.GetBytes(ReqStr);
                socket.Send(bPck);
                if (ConMode != 1)
                {
                    if (ConMode == 9001)
                    {
                        string sGoodPack = "HTTP/1.1 100 Continue" + "\r\n\r\n";
                        string sTmpResp = ""; byte[] bTmpResp = new byte[1]; int iTmpBytes;
                        while ((iTmpBytes = socket.Receive(bTmpResp, 0, 1, SocketFlags.None)) > 0)
                        {
                            sTmpResp += Encoding.ASCII.GetString(bTmpResp, 0, iTmpBytes);
                            if (sTmpResp.StartsWith(sGoodPack))
                            {
                                break;
                            }
                            if (sTmpResp.Length >= sGoodPack.Length && !sTmpResp.StartsWith(sGoodPack))
                            {
                                throw new Exception("#02-0006");
                            }
                        }
                    }
                    socket.Send(Postdata);
                }
                if (!ParseHeader())
                {
                    if (sResponseCode != "")
                    {
                        throw new Exception("#02-0004_" + sResponseCode);
                    }
                    throw new Exception("#02-0003");
                }

                // ~~~ Download file ~~~ \\
                lSpdLastTick = Tick();
                byte[] RecvBuffer = new byte[cSize]; int nBytes, nTotalBytes = 0;
                while ((nBytes = socket.Receive(RecvBuffer, 0, cSize, SocketFlags.None)) > 0)
                {
                    nTotalBytes += nBytes; State = ReqState.Downloading; lSpdPacketCnt++; cSpeed();
                    Progress     = Math.Round(((double)100 - ((double)cLength - (double)nTotalBytes) * (double)100 / (double)cLength), 1);
                    msResponse.Write(RecvBuffer, 0, nBytes);
                }
                socket.Close();

                // ~~~ Return text ~~~ \\
                if (ReturnStr)
                {
                    //TODO: Parse encoding from headers
                    msResponse.Seek(0, SeekOrigin.Begin);
                    System.IO.StreamReader utf = new StreamReader(msResponse, Encoding.UTF8);
                    sResponse = utf.ReadToEnd(); //Close and Dispose raeps msResponse
                }
                if (Filename != "")
                {
                    System.IO.FileStream fs = new FileStream(Filename, FileMode.Create);
                    msResponse.WriteTo(fs); fs.Flush(); fs.Close(); fs.Dispose();
                }
                msResponse.Seek(0, SeekOrigin.Begin);
                State    = ReqState.Completed;
                Progress = 100; isReady = true;
            }
            catch (Exception ex)
            {
                wrExThrow(ex.Message, ex.StackTrace);
            }
        }
Exemple #21
0
        private void bw_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                // ~~~ Create socket, set timeout ~~~ \\
                socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                IPEndPoint RHost = new IPEndPoint(Dns.GetHostEntry(URI.Host).AddressList[0], URI.Port);
                if (iTimeout != -1)
                {
                    socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, iTimeout);
                    socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, iTimeout);
                    BackgroundWorker bwTimeout = new BackgroundWorker();
                    bwTimeout.DoWork += new DoWorkEventHandler(bwTimeout_DoWork);
                    bwTimeout.RunWorkerAsync();
                }

                // ~~~ Create request, send request ~~~ \\
                State = ReqState.Connecting;
                try
                {
                    socket.Connect(RHost);
                }
                catch
                {
                    throw new Exception("#02-0002");
                }
                State = ReqState.Requesting;
                string ReqStr = ConQHdr + " " + URI.PathAndQuery + " HTTP/1.1\r\n" + outHeaders;
                //Response = ReqStr; isReady = true; return;
                byte[] bPck = System.Text.Encoding.ASCII.GetBytes(ReqStr);
                socket.Send(bPck);
                if (ConMode != 1)
                {
                    if (ConMode == 3)
                    {
                        string sGoodPack = "HTTP/1.1 100 Continue" + "\r\n\r\n";
                        string sTmpResp = ""; byte[] bTmpResp = new byte[1]; int iTmpBytes;
                        while ((iTmpBytes = socket.Receive(bTmpResp, 0, 1, SocketFlags.None)) > 0)
                        {
                            sTmpResp += Encoding.ASCII.GetString(bTmpResp, 0, iTmpBytes);
                            if (sTmpResp.StartsWith(sGoodPack))
                            {
                                break;
                            }
                            if (sTmpResp.Length >= sGoodPack.Length && !sTmpResp.StartsWith(sGoodPack))
                            {
                                throw new Exception("#02-0006");
                            }
                        }
                    }
                    socket.Send(Postdata);
                }
                if (!ParseHeader())
                {
                    if (ResponseCode != "")
                    {
                        throw new Exception("#02-0004_" + ResponseCode);
                    }
                    throw new Exception("#02-0003");
                }

                // ~~~ Find filename ~~~ \\
                string tFName = "";
                do
                {
                    tFName = tmpPath + "wanr_" + RandomChars(12) + ".tmp";
                }while (File.Exists(tFName));

                // ~~~ Download file ~~~ \\
                lSpdLastTick = Tick();
                FileStream   streamOut = File.Open(tFName, FileMode.Create, FileAccess.Write, FileShare.ReadWrite);
                BinaryWriter writer = new BinaryWriter(streamOut);
                byte[]       RecvBuffer = new byte[cSize]; int nBytes, nTotalBytes = 0;
                while ((nBytes = socket.Receive(RecvBuffer, 0, cSize, SocketFlags.None)) > 0)
                {
                    nTotalBytes += nBytes; State = ReqState.Downloading; lSpdPacketCnt++; cSpeed();
                    Progress     = Math.Round(((double)100 - ((double)cLength - (double)nTotalBytes) * (double)100 / (double)cLength), 1);
                    writer.Write(RecvBuffer, 0, nBytes);
                    if (ReturnStr)
                    {
                        Response += Encoding.ASCII.GetString(RecvBuffer, 0, nBytes);
                    }
                }
                streamOut.Flush(); streamOut.Close(); streamOut.Dispose();
                socket.Close();

                // ~~~ Verify download, return text ~~~ \\
                long tStart = Tick();
                if (!File.Exists(tFName))
                {
                    wrErrlog("Poll1 false");
                }
                while (!File.Exists(tFName))
                {
                    System.Threading.Thread.Sleep(10);
                    if (Tick() > tStart + 2000)
                    {
                        break;
                    }
                }
                if (!File.Exists(tFName))
                {
                    wrErrlog("Poll2 false");
                }
                if (File.Exists(tFName))
                {
                    if (ReturnStr)
                    {
                        System.IO.StreamReader strmIn = new System.IO.StreamReader(tFName, Encoding.GetEncoding("iso-8859-1"));
                        Response = strmIn.ReadToEnd(); strmIn.Close(); strmIn.Dispose();
                    }
                    if (Filename != "")
                    {
                        File.Delete(Filename); File.Move(tFName, Filename);
                    }
                    else
                    {
                        File.Delete(tFName);
                    }
                }
                else
                {
                    throw new Exception("#02-0001");
                }
                State = ReqState.Completed; Progress = 100; isReady = true;
            }
            catch (Exception ex)
            {
                wrExThrow(ex.Message, ex.StackTrace);
            }
        }
Exemple #22
0
        private void bw_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                IPEndPoint RHost = new IPEndPoint(Dns.GetHostEntry(URI.Host).AddressList[0], URI.Port);
                if (iTimeout != -1)
                {
                    socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, iTimeout);
                    socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, iTimeout);
                    BackgroundWorker bwTimeout = new BackgroundWorker();
                    bwTimeout.DoWork += new DoWorkEventHandler(bwTimeout_DoWork);
                    bwTimeout.RunWorkerAsync();
                }
                State = ReqState.Connecting; socket.Connect(RHost); State = ReqState.Requesting;
                if (ConMode == "POST")
                {
                    outHeaders.Add("Content-Type: application/x-www-form-urlencoded");
                }
                string ReqStr = ConMode + " " + URI.PathAndQuery + " HTTP/1.0\r\n" + outHeaders;
                if (ConMode == "POST")
                {
                    ReqStr += Postdata;
                }
                SentPacket = ReqStr + "\r\n\r\n>";
                byte[] bPck = System.Text.Encoding.ASCII.GetBytes(ReqStr);
                foreach (byte btPck in bPck)
                {
                    SentPacket += btPck + " ";
                }
                socket.Send(System.Text.Encoding.ASCII.GetBytes(ReqStr));
                if (ParseHeader())
                {
                    string tFName = "";
                    do
                    {
                        tFName = tmpPath + "wanr_" + RandomChars(6) + ".tmp";
                    }while (File.Exists(tFName));
                    FileStream   streamOut = File.Open(tFName, FileMode.Create, FileAccess.Write, FileShare.ReadWrite);
                    BinaryWriter writer = new BinaryWriter(streamOut);
                    byte[]       RecvBuffer = new byte[cSize]; int nBytes, nTotalBytes = 0;
                    while ((nBytes = socket.Receive(RecvBuffer, 0, cSize, SocketFlags.None)) > 0)
                    {
                        nTotalBytes += nBytes; State = ReqState.Downloading;
                        Progress     = Math.Round(((double)100 - ((double)cLength - (double)nTotalBytes) * (double)100 / (double)cLength), 1);
                        writer.Write(RecvBuffer, 0, nBytes);
                        if (ReturnStr)
                        {
                            Response += Encoding.ASCII.GetString(RecvBuffer, 0, nBytes);
                        }
                    }
                    streamOut.Flush(); streamOut.Close(); streamOut.Dispose();
                    socket.Close();

                    long tStart = Program.Tick();
                    if (!File.Exists(tFName))
                    {
                        wrErrlog("Poll1 false");
                    }
                    while (!File.Exists(tFName))
                    {
                        System.Threading.Thread.Sleep(10);
                        if (Program.Tick() > tStart + 2000)
                        {
                            break;
                        }
                    }
                    if (!File.Exists(tFName))
                    {
                        wrErrlog("Poll2 false");
                    }
                    if (File.Exists(tFName))
                    {
                        if (ReturnStr)
                        {
                            System.IO.StreamReader strmIn = new System.IO.StreamReader(tFName, Encoding.GetEncoding("iso-8859-1"));
                            Response = strmIn.ReadToEnd(); strmIn.Close(); strmIn.Dispose();
                        }
                        if (Filename != "")
                        {
                            File.Delete(Filename); File.Move(tFName, Filename);
                        }
                        else
                        {
                            File.Delete(tFName);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                wrExThrow(ex.Message, ex.StackTrace);
            }
            State = ReqState.Completed; Progress = 100; isReady = true;
        }