⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 stressclient.cpp

📁 mini http server,可以集成嵌入到程序中,实现简单的web功能
💻 CPP
📖 第 1 页 / 共 3 页
字号:
/*____________________________________________________________________________*\
 *

 Copyright (c) 1997-2003 John Roy, Holger Zimmermann. All rights reserved.

 These sources, libraries and applications are
 FREE FOR COMMERCIAL AND NON-COMMERCIAL USE
 as long as the following conditions are adhered to.

 Redistribution and use in source and binary forms, with or without
 modification, are permitted provided that the following conditions
 are met:

 1. Redistributions of source code must retain the above copyright
    notice, this list of conditions and the following disclaimer. 

 2. Redistributions in binary form must reproduce the above copyright
    notice, this list of conditions and the following disclaimer in
    the documentation and/or other materials provided with the
    distribution.

 3. The name of the author may not be used to endorse or promote products
    derived from this software without specific prior written permission.

 THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 IN NO EVENT SHALL THE AUTHORS OR ITS CONTRIBUTORS BE LIABLE FOR ANY
 DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
 GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 OF THE POSSIBILITY OF SUCH DAMAGE.

 *____________________________________________________________________________*|
 *
 * $Source: /cvsroot/pi3web/Pi3Web_200/Source/TestClnt/StressClient.cpp,v $
 * $Date: 2003/05/13 18:42:22 $
 *
 Description:
	Base class for all C++ handlers, provides a more comfortable interface
	above the raw Pi3 HTTP interface.


\*____________________________________________________________________________*/
//$SourceTop:$

#include <assert.h>
#include <ctype.h>
#include <stdio.h>

#include "StressClient.h"
#include "PIString.h"
#include "DeQuote.h"
#include "PICompat.h"
#include "HTTPDefs.h"
#include "PIStrStr.h"
#include "Pi3API.h"
#include "StrToken.h"

/*____________________________________________________________________________*\
 *
 Description:
\*____________________________________________________________________________*/
#if 0
	/*
	** HTML documentation for this handler
	*/
/*___+++HTMLDOC_BEGIN+++___*/
Name:
	StressClient

Description:
	Load and execute an HTTP client handler. The client executes
	the configured test cases in a ordered or a random sequence.
	In collaboration with the Pi3 platform multiprocessing and
	multithreading capabilities high load and stress tests of
	HTTP servers could be performed.

Options:

<TABLE BORDER=1>
<TH>Option
<TH>Default
<TH>Values
<TH>Short Description
<TH>Example(s)

<TR>
<TD>TestCase
<TD>-
<TD>Method [SP] URI [SP] Protocol
<TD>A simple HTTP request line
<TD>TestCase "GET /index.htm HTTP/1.1"

<TR>
<TD>TestFile
<TD>-
<TD>path to an existing file
<TD>A more complex HTTP request stored in a file.
<TD>TestFile "..\Tests\t100.dat:404"

<TR>
<TD>FileMask
<TD>-
<TD>path to a group of files with wildcards
<TD>A group of HTTP requests, each in a separate file.
<TD>FileMask "..\Tests\*.dat"

<TR>
<TD>Random
<TD>Off
<TD>On/Off
<TD>Sets random or sequential order of requests
<TD>Random On

<TR>
<TD>KeepOpen
<TD>On
<TD>On/Off
<TD>If set, the KeepAlive protocol is used between requests
<TD>KeepOpen Off

<TR>
<TD>KeepOpenCount
<TD>10
<TD>A valid unsigned number
<TD>Number of kept alive HTTP requests
<TD>KeepOpenCount 1000

<TR>
<TD>KeepOpenTimeout
<TD>5
<TD>A valid unsigned number
<TD>Timeout value between kept alive requests in seconds
<TD>KeepOpenTimeout 10

</TABLE>
<STRONG>-</STRONG> in the <IT>default</IT> indicates no default<BR>
<STRONG>+</STRONG> in the <IT>default</IT> indicates the field is mandatory<BR>

<H4>Description of Options</H4>
<H5>TestCase</H5>
This is the simple way to add a new test case to the test client. The HTTP
request line is written directly into the configuration of the StressClient
object. This is only feasable for single line requests, without a body or
additional headers.
<p>The handler will add mandatory headers, if required for the respective
protocol version, e.g. the <i>Host:</i> header in HTTP/1.1.
<p>An expected HTTP status code could be set separated by a colon. If the
server returns another status, a console message is written by the handler.

<H5>TestFile</H5>
This is a more comfortable way to add a new test case to the test client.
The contents of the given text file is sent to the server without additions
by the handler.
<p>An expected HTTP status code could be set separated by a colon. If the
server returns another status, a console message is written by the handler.

<H5>FileMask</H5>
This is the most comfortable way to add a whole group of test cases to the
test client. The file mask will be expanded on startup and all matching files
will be used. The contents of the given text files is sent to the server
as separate requests without additions by the handler.
<p>An expected HTTP status code could be set separated by a colon. If the
server returns another status, a console message is written by the handler.
All requests in a group should expect the same status code in that case.

Phase:
	HANDLE

Returns:
	PIAPI_COMPLETED, PIAPI_ERROR according to the handler status.

Note:
	The handler could be used with the MultithreadedIOServer and the
	UnixDaemon for high load tests. The underlying TCPIOObject is simply
	switched to active (client) sockets. The address of the server to
	test is configured in the IOObject using the following parameters
	<pre>
	BindHost localhost
	BindPort 80
	</pre>
	<p>If a socket is connected, a new thread is started and this handler
	will be executed. Test cases are performed in a loop until the KeepAlive
	condition becomes false.
	<p>If the tested server does not accept more connections during tests,
	a critical IO error will occur and the Pi3 platform is shut down.
	<p>The test client will be started from the Pi3Client/bin folder -
	<pre>
	./Pi3 ../Conf/StressClient.pi3
	</pre>

Example:
	<PRE>
	&lt;Object&gt;
		Name ClientIOObject
		Class TCPIPIOClass
		Type Active
		BindHost localhost
		BindPort 80
		AcceptTimeout 1000
		RecvTimeout 30
		SendTimeout 30
		PeerIPVariable STRING:RemoteAddr
		PeerHostNameVariable STRING:RemoteHost
		LocalAddressVariable STRING:LocalAddr
		ServerPortVariable RFC822:ServerPort
		Flags OwnDB|SetPeerAddress|SetLocalAddress
	&lt;/Object&gt;

	&lt;Object&gt;
		Name ThreadPoolDispatcher
		Class MultiThreadedIOServerClass
		IOObject ClientIOObject
		LogicObject StressClient
		MaxThreads 5
		ExitAfter 1000
	&lt;/Object&gt;

	&lt;Object&gt;
		Name Main
		Class UNIXDaemonClass
		ServerObject ThreadPoolDispatcher
		PIDFile "../Logs/pid.log"
		RLimitCpu Maximum
		LockFileName "../Logs/lockfile.txt"
		Message "Pi3Web stress test client started"
		NumberOfProcesses 5
	&lt;/Object&gt;

	&lt;Object&gt;
		Name StressClient
		Class StressClientClass
		TestCase "GET /index.htm HTTP/1.1"
		TestCase "GET /pidocs/Features/test4.php3 HTTP/1.1:401"
		TestFile "..\Tests\t10.dat"
		TestFile "..\Tests\t100.dat:404"
		FileMask "..\Tests\*.dat"
		FileMask "..\Tests2\*.dat"
		Random Off
		KeepOpen On
		KeepOpenCount 10
		KeepOpenTimeout 5
	&lt;/Object&gt;
	</PRE>

/*___+++HTMLDOC_END+++___*/
#endif


/*____________________________________________________________________________*\
 *
 Function:
 Synopsis:
 Description:
\*____________________________________________________________________________*/
StressClient::StressClient( PIObject *pObject, int iArgc, const char *ppArgv[] ) :
	pObject( pObject ),
	iOK( 1 ),
	iKeepOpenCount( 10 ),
	iProtocol( PR_UNKNOWN ),
	iKeepAlive( 1 ),	
	iAliveTimeout( 50 ),
	pFKRecvTimeout( PIDB_getFastKey( KEY_INT_RECVTIMEOUT, PIDBTYPE_OPAQUE ) ),
	pFKTestfile( PIDB_getFastKey( KEY_INT_TESTFILE, PIDBTYPE_STRING ) ),
	pFKHost( PIDB_getFastKey( KEY_HTTP_HOST, PIDBTYPE_RFC822 ) ),
	iRandom( 0 ),
	iCurrentTest( 0 ),
	iMaxTest( 0 ),
	sUserAgent( "Pi3Web-Client/1.0" ),
	sVirtualHost( 0 ),
	logfile( PIPLATFORM_FD_INVALID ),
	sLogfile( 0 ),
	sOpenMode( "a" ),
	pTestcaseDB( PIDB_new( 0, "StressTests") )
{
    iOK = PIObject_readParameters( pObject, iArgc, ppArgv, ParameterFn,	this );

	HTTPCore_initClient();

	// Adjust testcase counters
	if (iCurrentTest)
		{
		iMaxTest = iCurrentTest - 1;
		iCurrentTest = 0;
		};

}


/*____________________________________________________________________________*\
 *
 Function:
 Synopsis:
 Description:
\*____________________________________________________________________________*/
StressClient::~StressClient()
{
	HTTPCore_cleanupClient();
	PIDB_delete( pTestcaseDB );
	pTestcaseDB = 0;
}


/*____________________________________________________________________________*\
 *
 Function:
 Synopsis:
 Description:
	Verify the HTTP request line and divide it into components. Returns
	INT_CONTINUE on success or an HTTP error status code on error.

	Assumes pLine is NULL terminated at pLine[iLineLen].

	On success instantiates all values to at least an empty string with the
	exception of the proxy values which will all be instantiated if
	ppProxyProtocol is instantiated.

\*____________________________________________________________________________*/
static int SplitRequestLine(
	char *pLine, 
	int iLineLen,
	const char **ppMethod,
	const char **ppProxyProtocol,
	const char **ppProxyHost,
	int *piProxyHostLen,
	const char **ppProxyPort,
	int *piProxyPortLen,
	const char **ppPath,
	const char **ppQueryString,
	const char **ppProtocol
	)
{
	assert( pLine );
	assert( iLineLen );
	assert( ppMethod );
	assert( ppProxyProtocol );
	assert( ppProxyHost );
	assert( piProxyHostLen );
	assert( ppProxyPort );
	assert( piProxyPortLen );
	assert( ppPath );
	assert( ppProtocol );

	*ppProtocol = "";	/* --- this is done because protcol is optional, i.e.
						HTTP/0.9 doesn't send one
						--- */
	/* ---
	method
	--- */
	int i = 0;
	for( ; i<iLineLen && !(isspace(pLine[i])); i++);
	*ppMethod = pLine;
	if ( i==iLineLen ) { return ST_BADREQUEST; };
	pLine[i]='\0'; i++;
	for(; i<iLineLen && (isspace(pLine[i])); i++);
	pLine = &( pLine[i] ); iLineLen -= i; i=0; 

	/* ---
	pLine now points at the component following the method
	--- */

	/* --- URL path must exist --- */
	if ( i==iLineLen )
		{ return ST_BADREQUEST; };

	/* ---
	proxy host and port
	--- */
	if ( (*pLine!='/') && (*pLine!='*'))
		{
		/* --- assume proxy host and port specification --- */
		for(;
			(i+2)<iLineLen &&
			strncmp(&(pLine[i]), "://", 3) && !(isspace(pLine[i])); i++)
			{ pLine[i] = tolower( pLine[i] ); };
		if ( !strncmp( &(pLine[i]), "://", 3 ) )
			{
			*ppProxyProtocol = pLine; pLine[i] = '\0';
			i += 3;
			pLine = &( pLine[i] ); iLineLen -= i; i=0;

			/* --- pLine now points at proxy host --- */
			*ppProxyHost = pLine;
			for(;	i<iLineLen &&
					pLine[i]!=':' &&
					pLine[i]!='/' &&
					!(isspace(pLine[i])); i++);
			*piProxyHostLen = i;
			if ( pLine[i]==':' ) 
				{
				i++;
				pLine = &( pLine[i] ); iLineLen -= i; i=0;

				/* --- pLine now points at proxy port --- */
				*ppProxyPort = pLine;
				for(; i<iLineLen && pLine[i]!='/' && !(isspace(pLine[i])); i++);
				*piProxyPortLen = i;
				}
			else
				{
				*ppProxyPort = "";
				*piProxyPortLen = 0;
				};
			pLine = &( pLine[i] ); iLineLen -= i; i=0;
			}
		else
			{
			/* ---
			The URL path didn't start with '/' but it wasn't a proxy request

			NOTE: Maybe this should raise a gateway error instead of the
			generic bad request error.

			--- */
			return ST_BADREQUEST;
			};
		};

	/* ---	
	pLine now points at first character of URL path

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -