from:http://iunknown.javaeye.com/blog/78561
關鍵字: C++ libevent spserver http embedded web 服務器
看到這個題目,估計很多人會問:為什么要再實現一個 web 服務器?
這里有幾個原因:
1.這是一個 web 服務器框架,不是一個完整的 web 服務器。也就是說 SPWebServer 提供的是一套 API 和類庫,可以方便地集成到現有的應用程序中。可以稱 SPWebServer 為 embedded web server 。
2.有些時候,我們需要的不是一個功能強大完整的 web 服務器(例如 apache ),我們只是需要一個能提供最基本的 http 功能的服務器框架。比如要用 C/C++ 實現 XML-RPC,JSON-RPC 服務器端,或者為 jabberd 實現一個 http bind 的時候。這些場景下,也可以使用 apache,但是使用 embedded web server 可以簡化配置。
3.在如下的場合中,apache 顯得不合適,而 embedded web server 卻正好合適:在一個現有的應用程序中,用 http 接口來提供一些簡單的控制和統計功能。
基于以上原因,也為了
1.豐富 SPServer 項目(請參考: SPServer : 一個基于 Half-Sync/Half-Async 模式的高并發 server 框架)的功能;
2.正好作為 SPServer 框架的一個比較好的示范例子;
因此基于 SPServer 框架實現了一個 web 服務器框架。
源代碼下載:
http://spserver.googlecode.com/files/spserver-0.5.src.tar.gz
http://code.google.com/p/spserver/downloads/list
下面來看一個使用 SPWebServer 的簡單例子。

class SP_HttpEchoHandler : public SP_HttpHandler
{
public:

SP_HttpEchoHandler()
{}

virtual ~SP_HttpEchoHandler()
{}

virtual void handle( SP_HttpRequest * request, SP_HttpResponse * response )
{
response->setStatusCode( 200 );
response->appendContent( "<html><head>"
"<title>Welcome to simple http</title>"
"</head><body>" );

char buffer[ 512 ] =
{ 0 };
snprintf( buffer, sizeof( buffer ),
"<p>The requested URI is : %s.</p>", request->getURI() );
response->appendContent( buffer );
snprintf( buffer, sizeof( buffer ),
"<p>Client IP is : %s.</p>", request->getClientIP() );
response->appendContent( buffer );

for( int i = 0; i < request->getParamCount(); i++ )
{
snprintf( buffer, sizeof( buffer ),
"<p>Param - %s = %s<p>", request->getParamName( i ),
request->getParamValue( i ) );
response->appendContent( buffer );
}

for( int i = 0; i < request->getHeaderCount(); i++ )
{
snprintf( buffer, sizeof( buffer ),
"<p>Header - %s: %s<p>", request->getHeaderName( i ),
request->getHeaderValue( i ) );
response->appendContent( buffer );
}

if( NULL != request->getContent() )
{
response->appendContent( "<p>" );
response->appendContent( request->getContent(),
request->getContentLength() );
response->appendContent( "</p>" );
}
response->appendContent( "</body></html>\n" );
}
};

class SP_HttpEchoHandlerFactory : public SP_HttpHandlerFactory
{
public:

SP_HttpEchoHandlerFactory()
{}

virtual ~SP_HttpEchoHandlerFactory()
{}

virtual SP_HttpHandler * create() const
{
return new SP_HttpEchoHandler();
}
};
//---------------------------------------------------------
int main( int argc, char * argv[] )


{
int port = 8080;
SP_Server server( "", port,
new SP_HttpHandlerAdapterFactory( new SP_HttpEchoHandlerFactory() ) );
server.runForever();
return 0;
}

上面的代碼演示的是一個 http echo server ,即把 client 發過來的請求信息顯示在頁面上。
在最簡單的情況下,使用 SPWebServer 需要實現兩個類:SP_HttpHandler 的子類 和 SP_HttpHandlerFactory 的子類。
SP_HttpHandler 的子類負責處理具體的 http 請求。
SP_HttpHandlerFactory 的子類協助 spserver 為每一個連接創建一個 SP_HttpHandler 子類實例。
在實現過程中,使用了 Adapter 模式,把 SP_HttpHandler 和 SP_HttpHandlerFactory 適配為 SP_Handler 和 SP_HandlerAdapterFactory。這兩個 Adapter 都已經實現,不需要使用者來實現。