Pre-Emptive Multithreading Web Spider

zhaozj2021-02-08  234

Pre-Emptive Multithreading Web Spider

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 used 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 .

.

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 in Put Is When The Thread Count Exceedes Maximum_Wait_Objects Which is defined as 64.

.

CspideThread * 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 CspideThread :: 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 capital thread country

// Synchronizied. if the number of threads is greater tourimum_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_CheckurnName;

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 tagurnstatus

{

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 not seem to keep the thread count below 64 at all times limit of 32,767 url links in the clistview would not 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

转载请注明原文地址:https://www.9cbs.com/read-1718.html

New Post(0)