I'm writing a C# app that uses HttpWebRequest & HttpWebResponse objects to download files from a web server using async I/O on a Toshiba e800 w/ WM2003SE. My goal is to create a simple wrapper that makes background downloading easy and can also download multiple files at once.
My code works, but is very unreliable. Most of the time, the "int Bytes = tWS.webStr.EndRead(inAR);" line returns 0 bytes (meaning end of stream) after just a few reads -- way before the actual end of the stream, which is correctly reported by the webRes.ContentLength property. I resume the download as a work-around.
I'm totally new to C# and programming PPC's in general, so please let me know if there are any obvious problems in my code. Below are the guts of my app. To start a harvester, to this:
Note that I'm only using one download slot in this test, but multiple slots work and seem to behave no differently than just one.
... and here's the beast...
My code works, but is very unreliable. Most of the time, the "int Bytes = tWS.webStr.EndRead(inAR);" line returns 0 bytes (meaning end of stream) after just a few reads -- way before the actual end of the stream, which is correctly reported by the webRes.ContentLength property. I resume the download as a work-around.
I'm totally new to C# and programming PPC's in general, so please let me know if there are any obvious problems in my code. Below are the guts of my app. To start a harvester, to this:
- Code:
private httpHarvester Harvey;
private ListFile[] fl;
...
fl = new ListFile[4]; // or however many
Harvey = new httpHarvester(1, fl, this);
...
// Assign the same URL (from txtBox1) to many filenames
for (int i = 0; i < fl.Length; i++)
fl[i] = new ListFile(textBox1.Text, "image" + (i + 1).ToString() + ".jpg");
// Start the harvester
Harvey.BeginHarvest();
Note that I'm only using one download slot in this test, but multiple slots work and seem to behave no differently than just one.
... and here's the beast...
- Code:
// This function belongs in the main form. Everything else could be put in its own file.
public void Log(string inTxt) {
// Multiline textboxes aren't very good debug output windows, but it works for this test...
textBox2.Text += inTxt + "\r\n";
textBox2.SelectionStart = textBox2.Text.Length - 1;
textBox2.ScrollToCaret();
textBox2.Update();
}
public class WebState {
public HttpWebRequest webReq;
public HttpWebResponse webRes;
public Stream webStr;
public httpReader HRO;
public int _eb, _gb, _eosc;
public WebState(HttpWebRequest inWebReq) {
webReq = inWebReq;
}
}
public class ListFile {
public bool Ready, Done;
public string URL, Filename;
public ListFile(string inURL, string inFilename) {
URL = inURL; Filename = inFilename; Ready = true;
}
}
public enum httpErr : int {
heNone = 0,
heDone, heReqErr, heGetErr,
}
// This performs the actual download from a web server
public class httpReader {
public delegate void GetCompleteHandler(httpErr inHE, string inDesc, httpReader inHO);
public event GetCompleteHandler GetComplete;
public int Time, ReqTimeLimit, GetTimeLimit;
public string URL;
private HttpWebRequest webReq;
private WebState webSt;
private BinaryWriter _bw;
private byte[] _buff;
private const int BUFFSIZE = 8192;
// These are mainly for debugging
private int _Slot;
private Form1 _pf;
public httpReader(Form1 inPF, int inSlot) {
Time = ReqTimeLimit = GetTimeLimit = 0;
_pf = inPF; _Slot = inSlot;
_buff = new byte[BUFFSIZE];
}
public void Tick(int inTickTime) { // for external timeout experi
Time += inTickTime;
}
private void Log(string inText) {
_pf.Log("{" + _Slot.ToString() + "} " + inText);
}
// Returns TRUE if succeeded, FALSE if failed
public bool GetFromURL(string inURL, Stream outStream) {
Time = 0;
URL = inURL;
Log("GetFromURL: " + inURL);
_bw = new BinaryWriter(outStream);
try {
webReq = (HttpWebRequest)HttpWebRequest.Create(inURL);
//webReq.ContinueDelegate = new HttpContinueDelegate(tmp);
webReq.Timeout = ReqTimeLimit;
webSt = new WebState(webReq);
webSt._gb = webSt._eosc = 0;
webSt.HRO = this;
webReq.BeginGetResponse(new AsyncCallback(ResCallback), webSt);
} catch (Exception ex) {
Log("Exception (GetFromURL): " + ex.Message);
return false;
}
return true;
}
// HTTP server responded to the GET request, so end the request and begin downloading
private static void ResCallback(IAsyncResult inAR) {
WebState tWS = (WebState)inAR.AsyncState;
tWS.HRO.Log("Server responded. Downloading...");
try {
tWS.HRO.Time = 0; tWS.webReq.Timeout = 0;
tWS.webRes = (HttpWebResponse)tWS.webReq.EndGetResponse(inAR);
if (tWS._eosc == 0) tWS._eb = (int)tWS.webRes.ContentLength; // only read content length the 1st its seen (not when resuming)
tWS.HRO.Log("Expecting " + tWS._eb.ToString() + " bytes");
tWS.webStr = tWS.webRes.GetResponseStream();
tWS.webStr.BeginRead(tWS.HRO._buff, 0, BUFFSIZE, new AsyncCallback(GetCallback), tWS);
} catch (Exception ex) {
tWS.HRO.Log("Exception (ResCallback): " + ex.Message);
tWS.HRO.GetComplete(httpErr.heReqErr, ex.Message, tWS.HRO);
}
}
// HTTP server is sending data, so collect it
private static void GetCallback(IAsyncResult inAR) {
WebState tWS = (WebState)inAR.AsyncState;
try {
int Bytes = tWS.webStr.EndRead(inAR);
// The above line blocks and occasionally raises an exception, but only rarely
if (Bytes <= 0) { // End of data stream...???
if (tWS._eb <= tWS._gb || tWS._eosc >= 25) { // Close streams and call the complete callback
tWS.HRO.Log("Stream ends"); // (hack: close up if there have been 25 resume attempts)
tWS.HRO._bw.Close();
tWS.webRes.Close();
tWS.HRO.GetComplete(httpErr.heDone, "", tWS.HRO);
} else { // (hack: resume download when download size != expected size)
tWS.HRO.Log("Premature end of stream, resuming...");
tWS.webRes.Close();
tWS.webReq = (HttpWebRequest)HttpWebRequest.Create(tWS.HRO.URL);
tWS.webReq.Timeout = tWS.HRO.ReqTimeLimit;
tWS.webReq.AddRange(tWS._gb, tWS._eb); // Resume from last good position
tWS.webReq.BeginGetResponse(new AsyncCallback(ResCallback), tWS);
tWS._eosc++;
}
} else { // Data received, store it and get more...
tWS._gb += Bytes;
tWS.HRO.Log("Received " + Bytes.ToString() + " bytes (" + tWS._gb.ToString() + " total)");
tWS.HRO.Time = 0;
tWS.HRO._bw.Write(tWS.HRO._buff, 0, Bytes);
tWS.webStr.BeginRead(tWS.HRO._buff, 0, BUFFSIZE, new AsyncCallback(GetCallback), tWS);
}
} catch (Exception ex) {
tWS.HRO.Log("Exception (GetCallback): " + ex.Message);
tWS.HRO._bw.Close();
tWS.webRes.Close();
tWS.HRO.GetComplete(httpErr.heGetErr, ex.Message, tWS.HRO);
}
}
}
// This encapsulates the real workhorse and automates the download and file handling process
public class httpGetBot {
public bool Busy, Done, Failed;
public int Slot;
private Form1 _pf;
private FileStream _fs;
private httpReader _hro;
private bool Auto;
private int _li; // Currently-downlading file (index)
private ListFile[] _fl; // List of files to download
public httpGetBot(Form1 inParentForm, int inSlot) {
Busy = Done = Failed = false;
Slot = inSlot;
_pf = inParentForm;
_hro = new httpReader(_pf, Slot);
_hro.GetTimeLimit = 20000; _hro.ReqTimeLimit = 20000;
_hro.GetComplete += new httpReader.GetCompleteHandler(this.GetComplete);
}
// Returns TRUE if download should begin, or FALSE if there was a problem
public bool httpGet(string inURL, string inDestFile) {
try {
Log("Download to: " + inDestFile);
Busy = true;
_fs = new FileStream(inDestFile, FileMode.Create, FileAccess.Write, FileShare.Read);
return _hro.GetFromURL(inURL, _fs);
} catch (Exception ex) {
Log("Exception (httpGet): " + ex.Message);
Busy = false; Failed = true;
return false;
}
}
public void httpGetList(ListFile[] inFiles) {
_fl = inFiles; Auto = true;
GetNextFile();
}
// Find and get another file from the list that's waiting to be downloaded
private void GetNextFile() {
for (int i = 0; i < _fl.Length; i++) {
if (_fl[i].Ready) {
_li = i;
_fl[_li].Ready = _fl[_li].Done = false;
httpGet(_fl[_li].URL, _fl[_li].Filename);
break;
}
}
}
// When a download is complete, successful or not, this is called...
private void GetComplete(httpErr inErr, string inDesc, httpReader inHO) {
Done = true; Busy = false;
_fs.Close();
switch (inErr) {
case httpErr.heReqErr:
Failed = true;
Log("Request error: " + inDesc);
return;
case httpErr.heGetErr:
Failed = true;
Log("Get error: " + inDesc);
return;
}
if (Auto) {
Log("Done, starting next...");
_fl[_li].Done = true;
GetNextFile();
} else {
Log("Done!");
}
}
private void Log(string inText) {
_pf.Log("[" + Slot.ToString() + "] " + inText);
}
}
// This abstraction layer will eventually create each httpGetBot in a separate thread
public class httpHarvester {
private httpGetBot[] Bots;
private ListFile[] Files;
private Form1 _pf;
public httpHarvester(int inBots, ListFile[] inFiles, Form1 inParent) {
Files = inFiles;
_pf = inParent;
Bots = new httpGetBot[inBots];
for (int i = 0; i < Bots.Length; i++)
Bots[i] = new httpGetBot(_pf, i);
}
public void BeginHarvest() {
for (int i = 0; i < Bots.Length; i++)
Bots[i].httpGetList(Files);
}
}