1。SPServer簡介
http://www.javaeye.com/topic/59804
2。程式碼分析
我們從一個簡單的伺服器入手分析。以下代碼取自F:/spserver-0.9.5/spserver/testecho.cpp
/*<br /> * Copyright 2007 Stephen Liu<br /> * For license terms, see the file COPYING along with this library.<br /> */</p><p>#include <stdio.h><br />#include <stdlib.h><br />#include <string.h><br />#include <signal.h><br />#include <assert.h></p><p>#include "spporting.hpp"</p><p>#include "spmsgdecoder.hpp"<br />#include "spbuffer.hpp"</p><p>#include "spserver.hpp"<br />#include "sphandler.hpp"<br />#include "spresponse.hpp"<br />#include "sprequest.hpp"<br />#include "sputils.hpp"</p><p>class SP_EchoHandler : public SP_Handler {<br />public:<br />SP_EchoHandler(){}<br />virtual ~SP_EchoHandler(){}</p><p>// return -1 : terminate session, 0 : continue<br />virtual int start( SP_Request * request, SP_Response * response ) {<br />request->setMsgDecoder( new SP_MultiLineMsgDecoder() );<br />response->getReply()->getMsg()->append(<br />"Welcome to line echo server, enter 'quit' to quit./r/n" );</p><p>return 0;<br />}</p><p>// return -1 : terminate session, 0 : continue<br />virtual int handle( SP_Request * request, SP_Response * response ) {<br />SP_MultiLineMsgDecoder * decoder = (SP_MultiLineMsgDecoder*)request->getMsgDecoder();<br />SP_CircleQueue * queue = decoder->getQueue();</p><p>int ret = 0;<br />for( ; NULL != queue->top(); ) {<br />char * line = (char*)queue->pop();</p><p>if( 0 != strcasecmp( line, "quit" ) ) {<br />response->getReply()->getMsg()->append( line );<br />response->getReply()->getMsg()->append( "/r/n" );<br />} else {<br />response->getReply()->getMsg()->append( "Byebye/r/n" );<br />ret = -1;<br />}</p><p>free( line );<br />}</p><p>return ret;<br />}</p><p>virtual void error( SP_Response * response ) {}</p><p>virtual void timeout( SP_Response * response ) {}</p><p>virtual void close() {}<br />};</p><p>class SP_EchoHandlerFactory : public SP_HandlerFactory {<br />public:<br />SP_EchoHandlerFactory() {}<br />virtual ~SP_EchoHandlerFactory() {}</p><p>virtual SP_Handler * create() const {<br />return new SP_EchoHandler();<br />}<br />};</p><p>//---------------------------------------------------------</p><p>int main( int argc, char * argv[] )<br />{<br />sp_openlog( "testecho", LOG_CONS | LOG_PID | LOG_PERROR, LOG_USER );</p><p>int port = 3333;</p><p>assert( 0 == sp_initsock() );</p><p>SP_Server server( "", port, new SP_EchoHandlerFactory() );<br />server.setMaxConnections( 10000 );<br />server.setReqQueueSize( 10000, "Server busy!" );<br />server.runForever();</p><p>return 0;<br />}</p><p>
代碼在87行,初始化SP_Server伺服器類server對象,傳入對象new SP_EchoHandlerFactory()作為參數
SP_EchoHandlerFactory在73行初始化對象SP_EchoHandler。
90行server.runForever()啟動伺服器進入服務。
重要的類有兩個:
SP_Server(伺服器)
SP_Handler(協議處理器)
一個輔助類:
SP_HandlerFactory(協議處理器工廠)
38行-58行代碼提示出其他重要的類:
SP_Request(請求,封裝用戶端發送資料)
SP_Response(回應,封裝伺服器回送資料)
SP_MultiLineMsgDecoder(多行訊息解析器,解析用戶端請求)