1。SPServer简介
http://www.javaeye.com/topic/59804
2。代码分析
我们从一个简单的服务器入手分析。以下代码取自F:/spserver-0.9.5/spserver/testecho.cpp
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <assert.h>
#include "spporting.hpp"
#include "spmsgdecoder.hpp"
#include "spbuffer.hpp"
#include "spserver.hpp"
#include "sphandler.hpp"
#include "spresponse.hpp"
#include "sprequest.hpp"
#include "sputils.hpp"
class SP_EchoHandler : public SP_Handler {
public:
SP_EchoHandler(){}
virtual ~SP_EchoHandler(){}
// return -1 : terminate session, 0 : continue
virtual int start( SP_Request * request, SP_Response * response ) {
request->setMsgDecoder( new SP_MultiLineMsgDecoder() );
response->getReply()->getMsg()->append(
"Welcome to line echo server, enter 'quit' to quit./r/n" );
return 0;
}
// return -1 : terminate session, 0 : continue
virtual int handle( SP_Request * request, SP_Response * response ) {
SP_MultiLineMsgDecoder * decoder = (SP_MultiLineMsgDecoder*)request->getMsgDecoder();
SP_CircleQueue * queue = decoder->getQueue();
int ret = 0;
for( ; NULL != queue->top(); ) {
char * line = (char*)queue->pop();
if( 0 != strcasecmp( line, "quit" ) ) {
response->getReply()->getMsg()->append( line );
response->getReply()->getMsg()->append( "/r/n" );
} else {
response->getReply()->getMsg()->append( "Byebye/r/n" );
ret = -1;
}
free( line );
}
return ret;
}
virtual void error( SP_Response * response ) {}
virtual void timeout( SP_Response * response ) {}
virtual void close() {}
};
class SP_EchoHandlerFactory : public SP_HandlerFactory {
public:
SP_EchoHandlerFactory() {}
virtual ~SP_EchoHandlerFactory() {}
virtual SP_Handler * create() const {
return new SP_EchoHandler();
}
};
//---------------------------------------------------------
int main( int argc, char * argv[] )
{
sp_openlog( "testecho", LOG_CONS | LOG_PID | LOG_PERROR, LOG_USER );
int port = 3333;
assert( 0 == sp_initsock() );
SP_Server server( "", port, new SP_EchoHandlerFactory() );
server.setMaxConnections( 10000 );
server.setReqQueueSize( 10000, "Server busy!" );
server.runForever();
return 0;
}
代码在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(多行消息解析器,解析客户端请求)