最后我们可以根据上层的具体需求提供特定的 _OnMessage
函数,我们这里就实现一个简单回声功能。
#include "TcpServer.hpp"
#include "Calculator.hpp"
#include <functional>
#include <memory>
void DefaultOnMessage(std::weak_ptr<Connection> conn)
{
if (conn.expired())
return;
auto connection_ptr = conn.lock();
Calculator calculator;
std::string response_str = "echo $: ";
std::cout << "上层得到了数据: " << connection_ptr->Inbuffer();
response_str+=connection_ptr->Inbuffer();
// response_str 发送出去
connection_ptr->AppendOutBuffer(response_str);
auto tcpserver = connection_ptr->_tcp_server_ptr.lock();
tcpserver->Sender(connection_ptr);
}
int main(int argc, char *argv[])
{
if (argc != 2)
{
Usage(argv[0]);
exit(1);
}
uint16_t port = std::stoi(argv[1]);
std::shared_ptr<TcpServer> Reactor(new TcpServer(port, DefaultOnMessage));
Reactor->InitServer();
Reactor->Loop();
return 0;
}