简陋RPC理解实现
作者:互联网
详情见注解
#include <iostream>
#include <list>
#include <map>
#include <cstring>
#include <iostream>
#include <memory>
#include <functional>
#include <boost/asio.hpp>
#include <boost/bind/bind.hpp>
/*
* Async Server
*/
using namespace boost::asio;
typedef std::shared_ptr<ip::tcp::socket> socket_ptr;
bool main_loop = true;
io_service ioserver;
ip::tcp::endpoint ep { ip::tcp::v4(), 2021};
ip::tcp::acceptor accer {ioserver, ep};
class IgnoreException:public std::exception {
public:
};
// 父类提供接口
class AbsHandler{
public:
virtual const std::string execute(){
}
virtual void operator()(){
}
};
class SendHandleMsg:public AbsHandler {
public:
virtual const std::string execute() override{
return "MMMMM";
}
};
class SendCutMsg:public AbsHandler{
public:
virtual const std::string execute() override {
return "wo co ni daye";
}
};
class QuitCmd:public AbsHandler{
public:
virtual const std::string execute() override {
throw boost::system::error_code();
}
};
//初始化调用对象,可能会有更复杂的调用机制需要另外设计。
class Controler{
public:
Controler(){
//初始化命令以及对象,也可以用XML等文本生成或重新配置。
handler["callme"] = std::make_shared<SendHandleMsg>();
handler["funcme"] = std::make_shared<SendCutMsg>();
handler["quit"] = std::make_shared<QuitCmd>();
}
std::shared_ptr<AbsHandler> rpc(const std::string sz){
if( handler.find(sz) == handler.cend()){
throw IgnoreException();
}
return handler[sz];
}
private:
std::map<std::string,std::shared_ptr<AbsHandler>> handler;
};
void handleConnection(socket_ptr, const boost::system::error_code&);
void startAAccept(socket_ptr);
void startAAccept(socket_ptr sok)
{
accer.async_accept(*sok,boost::bind(handleConnection, sok, boost::placeholders::_1));
}
void handleConnection(socket_ptr sok, const boost::system::error_code& err)
{
if(err) return;
char buff[1024];
bool cont = true;
while(cont){
try{
sok->read_some(buffer(buff));
std::string cmd (buff);
std::cout << "Received .. \n" << cmd << std::endl;
Controler ctrl;
// 调用的逻辑
sok->write_some(buffer(ctrl.rpc(cmd)->execute()));
std::memset(buff,0,sizeof(buff));
} catch( boost::system::error_code& err){
cont = false;
} catch (IgnoreException& e){
sok->write_some(buffer("Error cmd."));
std::memset(buff,0,sizeof(buff));
}
}
std::cout << "Disconection." << std::endl;
socket_ptr nsok (new ip::tcp::socket(ioserver));
startAAccept(nsok);
}
int main(int argc, char* argv[])
{
socket_ptr sok (new ip::tcp::socket(ioserver));
startAAccept(sok);
ioserver.run();
}
标签:std,const,简陋,ptr,RPC,理解,include,boost,public 来源: https://www.cnblogs.com/iusk/p/15137213.html