一、Ubuntu安装muduo
muduo库是基于boost开发的,确保先安装了boost
(对boost版本有要求),还需要先安装protobuf
,curl
库
库 | 版本 |
---|---|
boost | 1.70.0 |
protobuf | 3.14.0 |
curl | 7.74.0 |
muduo | 2.0.2 |
1、Ubuntu安装boost
# 更新资源列表
sudo apt update
# 安装依赖
sudo apt install build-essential python3-dev
# 下载boost源码1_70_0版本
wget https://boostorg.jfrog.io/artifactory/main/release/1.70.0/source/boost_1_70_0.tar.gz
# 解压并切换到解压后目录
tar -xvzf boost_1_70_0.tar.gz
cd boost_1_70_0
# 安装引导boost
./bootstrap.sh
sudo ./b2 install
sudo ldconfig
测试安装成功
#include <boost/regex.hpp>
#include <iostream>
int main() {
std::string s = "Boost Libraries";
boost::regex expr{"\\w+\\s\\w+"};
if (boost::regex_match(s, expr)) {
std::cout << "Boost is correctly installed and working!" << std::endl;
} else {
std::cout << "Boost installation test failed." << std::endl;
}
return 0;
}
2、Ubuntu安装protobuf
wget https://github.com/protocolbuffers/protobuf/releases/download/v3.14.0/protobuf-cpp-3.14.0.tar.gz
tar -xzf protobuf-cpp-3.14.0.tar.gz
cd protobuf-3.14.0
# 编译安装
./configure
make
sudo make install
sudo ldconfig
3、Ubuntu安装curl
wget https://curl.haxx.se/download/curl-7.74.0.tar.gz
tar -xzf curl-7.74.0.tar.gz
cd curl-7.74.0
# 编译并安装
./configure
make
sudo make install
sudo ldconfig
4、Ubuntu安装muduo
# 依赖
sudo apt update
sudo apt install build-essential cmake
# 下载moduo源码2.0.2版本
wget https://github.com/chenshuo/muduo/archive/refs/tags/v2.0.2.tar.gz
# 解压切换到目录
tar -xvzf v2.0.2.tar.gz
cd muduo-2.0.2
# 新建build目录存放编译文件,防止污染源码
mkdir build
cd build
# cmake编译
cmake ..
make -j$(nproc)
sudo make install
sudo ldconfig
简单echo服务器测试安装成功
#include <muduo/base/Logging.h>
#include <muduo/net/EventLoop.h>
#include <muduo/net/TcpServer.h>
using namespace muduo;
using namespace muduo::net;
void onConnection(const TcpConnectionPtr &conn) {
if (conn->connected()) {
LOG_INFO << "Connection established: " << conn->peerAddress().toIpPort();
} else {
LOG_INFO << "Connection closed: " << conn->peerAddress().toIpPort();
}
}
void onMessage(const TcpConnectionPtr &conn, Buffer *buf,
Timestamp receiveTime) {
std::string msg(buf->retrieveAllAsString());
LOG_INFO << "Received: " << msg;
conn->send(msg);
}
int main() {
Logger::setLogLevel(Logger::INFO);
EventLoop loop;
InetAddress listenAddr(8888);
TcpServer server(&loop, listenAddr, "EchoServer");
server.setConnectionCallback(onConnection);
server.setMessageCallback(onMessage);
server.start();
loop.loop();
}
测试结果为连接后,输入什么服务器就会返回什么。