因为muduo是依赖boost库的,因此我们先安装boost库
一、 安装boost库
进入官网boost官网
下载boost_1_70_0.tar.gz
运行命令
tar -zxvf boost_1_70_0.tar.gz #解压缩
cd boost_1_70_0 #进入文件夹
./bootstrap.sh #获得bjam文件
./bjam #运行它
sudo ./b2 install #进行安装, 必须要管理员权限,因为在这个过程中会把头文件和库放进/usr/
二、安装muduo
git clone https://github.com/chenshuo/muduo.git #下载源代码
把CMakeLists.txt里的option(MUDUO_BUILD_EXAMPLES "Build Muduo examples" ON")去掉,减少编译时间
./build.sh #执行编译命令
./build.sh install #安装muduo库
然后build.sh install会把muduo的头文件和lib库文件放到muduo-master的同级目录下的release-install-cpp11文件夹下面了
我们需要进入这个文件夹,然后把include文件夹里的东西移动到/usr/include中,把lib下的文件移动到/usr/local/lib中
mv include/muduo/ /usr/include/
mv lib/* /usr/local/lib/
三、测试,运行下面的代码
点击查看代码
#include <muduo/net/TcpServer.h>
#include <muduo/base/Logging.h>
#include <boost/bind.hpp>
#include <muduo/net/EventLoop.h>
// 使用muduo开发回显服务器
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::TcpServer server_;
};
EchoServer::EchoServer(muduo::net::EventLoop* loop,
const muduo::net::InetAddress& listenAddr)
: 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)
{
LOG_INFO << "EchoServer - " << conn->peerAddress().toIpPort() << " -> "
<< 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(8888);
EchoServer server(&loop, listenAddr);
server.start();
loop.loop();
}
编译命令
g++ main.cpp -lmuduo_net -lmuduo_base -lpthread -std=c++11
执行a.out,服务器就启动了
./a.out
另起一个客户端检测
echo "hello world" | nc localhost 8888