muduo库搭建客户端
muduo库搭建客户端
#include "include/muduo/net/TcpClient.h"
#include "include/muduo/net/EventLoopThread.h"
#include "include/muduo/net/TcpConnection.h"
#include "include/muduo/base/CountDownLatch.h"
#include <iostream>
#include <functional>class TranslateClient
{public:TranslateClient(const std::string&sip,int sport):_latch(1),_client(_loopthread.startLoop(),muduo::net::InetAddress(sip,sport),"Translate"){_client.setConnectionCallback(std::bind(&TranslateClient::onConnection,this,std::placeholders::_1));_client.setMessageCallback(std::bind(&TranslateClient::onMessage,this,std::placeholders::_1,std::placeholders::_2,std::placeholders::_3));}//连接服务器,需要进行阻塞等待连接建立成功之后再进行返回void connect(){_client.connect();//阻塞等待_latch.wait();}bool send(const std::string&msg){if(_conn->connected()){_conn->send(msg);return true;}return false;}private: //连接建立成功时候的回调函数,建立成功的时候,唤醒上面的阻塞void onConnection(const muduo::net::TcpConnectionPtr&conn){if(conn->connected()){_latch.countDown();_conn=conn;}else{//连接操作关闭_conn.reset();}}//收到消息时候的回调函数void onMessage(const muduo::net::TcpConnectionPtr& conn, muduo::net::Buffer* buf, muduo::Timestamp){std::cout<<"翻译结果为:"<<buf->retrieveAllAsString()<<std::endl;}private:muduo::CountDownLatch _latch;muduo::net::EventLoopThread _loopthread;muduo::net::TcpClient _client;muduo::net::TcpConnectionPtr _conn;
};int main()
{TranslateClient client("127.0.0.1",8085);client.connect();while(1){std::string buf;std::cin>>buf;client.send(buf);}return 0;
}
这段代码实现了一个基于 Muduo 网络库 的 TCP 翻译客户端,用于与之前分析的 TranslateServer
服务器进行交互。以下是代码的详细解析:
核心功能
- 连接服务器:客户端连接到指定 IP 和端口(如
127.0.0.1:8085
)。 - 发送翻译请求:用户输入英文单词或中文短语,客户端发送给服务器。
- 接收翻译结果:服务器返回翻译结果后,客户端打印到终端。
关键组件与逻辑
1. 类 TranslateClient
- 构造函数: 初始化
TcpClient
,绑定到服务器地址(sip:sport
)。 设置连接回调(onConnection
)和消息回调(onMessage
)。 - 成员变量:
_latch
:CountDownLatch
用于阻塞等待连接建立(同步机制)。_loopthread
:事件循环线程,处理网络 I/O。_client
:TCP 客户端对象。_conn
:保存当前有效的连接对象。
2. 连接管理
connect()
方法: 调用_client.connect()
发起连接。 通过_latch.wait()
阻塞,直到连接成功(onConnection
中调用_latch.countDown()
解除阻塞)。onConnection
回调: 连接成功时,保存TcpConnectionPtr
到_conn
,并解除阻塞。 连接断开时,重置_conn
。
3. 消息处理
send()
方法: 检查连接状态后,发送用户输入的消息到服务器。onMessage
回调: 收到服务器响应时,打印翻译结果(buf->retrieveAllAsString()
)。
4. 主函数 main
-
创建客户端对象,连接到本地服务器(
127.0.0.1:8085
)。 -
进入循环,等待用户输入并发送到服务器:
while (1) {std::string buf;std::cin >> buf; // 用户输入(如 "hello")client.send(buf); // 发送到服务器 }
工作流程
-
启动客户端:
./dict_client
-
用户交互: 输入
hello
→ 客户端发送到服务器。 服务器返回你好
→ 客户端打印翻译结果为: 你好
。 -
持续通信:循环等待用户输入,直到手动终止(
Ctrl+C
)。
技术亮点
- 同步连接等待: 使用
CountDownLatch
确保连接建立后再进行后续操作,避免竞态条件。 - 事件驱动:
EventLoopThread
处理网络 I/O,非阻塞且高效。 - 线程安全: 通过
TcpConnectionPtr
管理连接生命周期,避免悬空指针。
潜在改进
- 输入处理: 当前
std::cin
会忽略空格,建议改用std::getline
支持带空格的短语(如"thank you"
)。 - 错误处理: 添加连接失败或发送失败时的错误提示(如服务器未启动)。
- 退出机制: 支持输入特定命令(如
exit
)主动断开连接。
总结
这段代码是一个典型的 异步TCP客户端 实现,展示了如何通过 Muduo 库实现:
- 非阻塞连接建立
- 消息收发
- 事件回调机制
与之前分析的 TranslateServer
配合,即可构建完整的 C/S 架构翻译系统。