1. 说明
-
discard是连接到来时不做任何处理,代码比较短,贴在下面,后面的例子代码较长,还是自己找源码吧
-
实际就是一个DiscardServer类,有EventLoop* 和 TcpServer对象,重写连接到来函数和消息到来函数
2. 代码
/*
收到消息不做任何处理
*/
#include<muduo/base/Logging.h>
#include<muduo/net/EventLoop.h>
#include<muduo/net/TcpServer.h>
#include<muduo/net/InetAddress.h>
using namespace std;
using namespace muduo;
using namespace muduo::net;
class DiscardServer{
public:
DiscardServer(EventLoop* loop,const InetAddress& listen_addr)
:loop_(loop),server_(loop,listen_addr,"DiscardServer")
{
server_.setConnectionCallback(bind(&DiscardServer::on_connection,this,_1));
server_.setMessageCallback(bind(&DiscardServer::on_message,this,_1,_2,_3));
}
void start(){
server_.start();
}
private:
EventLoop* loop_;
TcpServer server_;
void on_connection(const TcpConnectionPtr& conn){
LOG_INFO<<"一个新连接:"<<conn->peerAddress().toIpPort()<<" to "
<<conn->localAddress().toIpPort();
}
void on_message(const TcpConnectionPtr& conn,Buffer* buf,Timestamp time){
string msg(buf->retrieveAllAsString());
LOG_INFO<<"收到消息:"<<msg;
}
};
int main(){
LOG_INFO << "pid = " << getpid() << ", tid = " << CurrentThread::tid();
EventLoop loop;
InetAddress listen_addr(11113);
DiscardServer server(&loop,listen_addr);
server.start();
loop.loop();
return 0;
}