this article was contributed by sim ayers.
the win32 api supports applications that are pre-emptively multithreaded. this is a very useful and powerful feature of win32 in writing mfc internet spiders. the spider project is an example of how to use preemptive multithreading to gather information on the web using a spider/robot with the mfc wininet classes.
this project produces a spidering software program that checks web sites for broken url links. link verification is done only on href links. it displays a continously updated list of urls in a clistview that reports the status of the href link. the project could be used as a template for gathering and indexing information to be stored in a database file for queries.
search engines gather information on the web using programs called robots. robots (also called web crawlers, spiders, worms, web wanderers, and scooters) automatically gather and index information from around the web, and then put that information into databases. (note that a robot will index a page, and then follow the links on that page as a source for new urls to index.) users can than construct queries to search these databases to find the information they want.
by using preemptive multithreading, you can index a web page of url links, start a new thread to follow each new url link for a new source of urls to index.
the project uses the mdi cdocument used with a custom mdi child frame to display a ceditview when downloading web pages and a clistview when checking url links. the project also uses the cobarray, cinternetsession, chttpconnection, chttpfile, and cwinthread mfc classes. the cwinthread class is used to produce multiple threads instead of using the asynchronous mode in cinternetsession, which is realy left over from the winsock 16 bit windows platform.
the spider project uses simple worker threads to check url links or download a web page. the cspiderthread class is derived from the cwinthread class so each cspiderthread object can use the cwinthread message_map() function. by declaring a "declare_message_map()" in the cspiderthread class the user interface is still responsive to user input. this means you can check the url links on one web server and at the same time download and open a web page from another web server. the only time the user interface will become unresponsive to user input is when the thread count exceedes maximum_wait_objects which is defined as 64.
in the constructor for each new cspiderthread object we supply the threadproc function and the thread paramters to be passed to the threadproc function.
cspiderthread* pthread; pthread = null; pthread = new cspiderthread(cspiderthread::threadfunc,pthreadparams); // create a new cspiderthread object
in the cspiderthread constructor we set the cwinthread* m_pthread pointer in the thread paramters structure so we can point to the correct instance of this thread;
pthreadparams->m_pthread = this;
the cspiderthread threadproc function
// simple worker thread proc function uint cspiderthread::threadfunc(lpvoid pparam) { threadparams * lpthreadparams = (threadparams*) pparam; cspiderthread* lpthread = (cspiderthread*) lpthreadparams->m_pthread; lpthread->threadrun(lpthreadparams); // use sendmessage instead of postmessage here to keep the current thread count // synchronizied. if the number of threads is greater than maximum_wait_objects (64) // the program will be come unresponsive to user input ::sendmessage(lpthreadparams->m_hwndnotifyprogress, wm_user_thread_done, 0, (lparam)lpthreadparams); // deletes lpthreadparams and decrements the thread count return 0; }
the structure passed to the cspiderthread threadproc function
typedef struct tagthreadparams { hwnd m_hwndnotifyprogress; hwnd m_hwndnotifyview; cwinthread* m_pthread; cstring m_pszurl; cstring m_contents; cstring m_strservername; cstring m_strobject; cstring m_checkurlname; cstring m_string; dword m_dwservicetype; dword m_threadid; dword m_status; urlstatus m_pstatus; internet_port m_nport; int m_type; bool m_rootlinks; }threadparams;
after the cspiderthread object has been created we use the creatthread function to start the execution of the new thread object.
if (!pthread->createthread()) // starts execution of a cwinthread object { afxmessagebox("cannot start new thread"); delete pthread; pthread = null; delete pthreadparams; return false; }
once the new thread is running we use the ::sendmessage function to send messages to the cdocument's-> clistview with the status structure of the url link.
if(pthreadparams->m_hwndnotifyview != null) ::sendmessage(pthreadparams->m_hwndnotifyview,wm_user_check_done, 0, (lparam) &pthreadparams->m_pstatus);
sturcture used for url status.
typedef struct tagurlstatus { cstring m_url; cstring m_urlpage; cstring m_statusstring; cstring m_lastmodified; cstring m_contenttype; cstring m_contentlength; dword m_status; }urlstatus, * purlstatus;
each new thread creats a new cmyinternetsession (derived from cinternetsession) object with enablestatuscallback set to true, so we can check the status on all internetsession callbacks. the dwcontext id for callbacks is set to the thread id.
bool cinetthread::initserver() { try { m_psession = new cmyinternetsession(agentname,m_nthreadid); int ntimeout = 30; // very important, can cause a server time-out if set to low // or hang the thread if set to high. /* the time-out value in milliseconds to use for internet connection requests. if a connection request takes longer than this timeout, the request is canceled. the default timeout is infinite. */ m_psession->setoption(internet_option_connect_timeout,1000* ntimeout); /* the delay value in milliseconds to wait between connection retries.*/ m_psession->setoption(internet_option_connect_backoff,1000); /* the retry count to use for internet connection requests. if a connection attempt still fails after the specified number of tries, the request is canceled. the default is five. */ m_psession->setoption(internet_option_connect_retries,1); m_psession->enablestatuscallback(true); } catch (cinternetexception* pex) { // catch errors from wininet //pex->reporterror(); m_psession = null; pex->delete(); return false ; } return true; }
the key to using the mfc wininet classes in a single or multithread program is to use a try and catch block statement surrounding all mfc wininet class functions. the internet is very unstable at times or the web page you are requesting no longer exist, which is guaranteed to throw a cinternetexception error.
try { // some mfc wininet class function } catch (cinternetexception* pex) { // catch errors from wininet //pex->reporterror(); pex->delete(); return false ; }
the maximum count of threads is initially set to 64, but you can configure it to any number between 1 and 100. a number that is too high will result in failed connections, which means you will have to recheck the url links.
a rapid fire succession of http requests in a /cgi-bin/ directory could bring a server to it's knees. the spider program sends out about 4 http request a second. 4 * 60 = 240 a minute. this can also bring a server to it's knees. be carefull about what server you are checking. each server has a server log with the requesting agent's ip address that requested the web file. you might get some nasty email from a angry web server administrator.
you can prevent any directory from being indexed by creating a robots.txt file for that directory. this mechanism is usually used to protect /cgi-bin/ directories. cgi scripts take more server resources to retrieve.
when the spider program checks url links it's goal is to not request too many documents too quickly. the spider program adheres somewhat to the standard for robot exclusion. this standard is a joint agreement between robot developers, that allows www sites to limit what url's the robot requests. by using the standard to limit access, the robot will not retrieve any documents that web server's wish to disallow.
before checking the root url, the program checks to see if there is a robots.txt file in the main directory. if the spider program finds a robots.txt file the program will abort the search. the program also checks for the meta tag in all web pages. if it finds a meta name="robots" content ="noindex,nofollow" tag it will not index the urls on that page.
build:
windows 95
mfc/vc++ 5.0
wininet.h dated 9/25/97
wininet.lib dated 9/16/97
wininet.dll dated 9/18/97
problems:
can't seem to keep the thread count below 64 at all times.
limit of 32,767 url links in the clistview
wouldn't parse all urls correctly, will crash program occasionally using cstring functions with complex urls.
resources:
internet tools - fred forester
multithreading applications in win32
win32 multithreaded programming
download source code and example (65 kb)
last updated: 21 june 1998
本文地址:http://com.8s8s.com/it/it3140.htm