My first muduo library server program

· Description: A simple echo server.
• The need to install the library: muduo, the Boost
· After installing the library, directly run the following command (+ compiler run) execute the program:

g++ -o test test.cpp -lmuduo_net -lmuduo_base -lpthread; ./test

test.cpp code is as follows:

#include <muduo/net/TcpServer.h>
#include <muduo/base/Logging.h>
#include <muduo/net/EventLoop.h>
#include <boost/bind.hpp>
class EchoServer{
public:
	EchoServer(muduo::net::EventLoop *loop, const muduo::net::InetAddress &listenAddr);
	void start();
private:
	void onConnection(const muduo::net::TcpConnectionPtr &conn);
	void onMessage(const muduo::net::TcpConnectionPtr &conn, muduo::net::Buffer *buf, muduo::Timestamp time);
	
	muduo::net::EventLoop *loop_;
	muduo::net::TcpServer server_;

};

EchoServer::EchoServer(muduo::net::EventLoop *loop, const muduo::net::InetAddress &listenAddr):loop_(loop), server_(loop, listenAddr, "EchoServer"){
	server_.setConnectionCallback(boost::bind(&EchoServer::onConnection, this, _1));
	server_.setMessageCallback(boost::bind(&EchoServer::onMessage, this, _1, _2, _3));
}

void EchoServer::start(){
	server_.start();
}

void EchoServer::onConnection(const muduo::net::TcpConnectionPtr &conn){ // TCP连接与断开时都会调用它
	LOG_INFO << "EchoServer - client(" << conn->peerAddress().toIpPort() << ") -> server(" << conn->localAddress().toIpPort() << ") is " << (conn->connected() ? "UP":"DOWN");
}

void EchoServer::onMessage(const muduo::net::TcpConnectionPtr &conn, muduo::net::Buffer *buf, muduo::Timestamp time){
	muduo::string msg(buf->retrieveAllAsString()); // 取走数据
	LOG_INFO << conn->name() << "echo " << msg.size() << "bytes, " << "data received at " << time.toString();
	conn->send(msg);
}

int main()
{
	LOG_INFO << "pid = " << getpid();
	muduo::net::EventLoop loop;
	muduo::net::InetAddress listenAddr(2007);
	EchoServer server(&loop, listenAddr);
	server.start();
	loop.loop();
    return 0;
}

Results are as follows:
Here Insert Picture Description
the Telnet server test program (telnet server address port number):

telnet 192.168.31.225 2007

Test results are as follows:
Here Insert Picture Description
Here Insert Picture Description


Reference "Linux multi-threaded server-side programming."

Published 92 original articles · won praise 2 · Views 3410

Guess you like

Origin blog.csdn.net/zxc120389574/article/details/105219691
Recommended