c++写一段tcp心跳包代码
时间: 2024-10-26 22:17:01 浏览: 17
C/C++基于VS开发的modbustcp源程序.rar
3星 · 编辑精心推荐
在C++中,TCP心跳包通常用于检查连接是否依然活跃。这里是一个简单的示例,展示如何创建一个发送心跳包的基本客户端和服务器程序。这个例子使用了`boost::asio`库来进行网络编程:
```cpp
#include <boost/asio.hpp>
#include <iostream>
// 心跳数据
const std::string HEARTBEAT = "Hello, Heartbeat!";
// 客户端函数
void send_heartbeat(tcp::socket& socket) {
boost::array<char, HEARTBEAT.size() + 1> buffer;
std::copy(HEARTBEAT.begin(), HEARTBEAT.end(), buffer.begin());
buffer[buffer.size() - 1] = '\0'; // 添加结束符
boost::asio::write(socket, boost::asio::buffer(buffer));
}
// 服务器函数(接收并回应心跳)
void handle_heartbeat(tcp::socket& socket) {
char data[HEARTBEAT.size() + 1];
size_t len = boost::asio::read(socket, boost::asio::buffer(data), HEARTBEAT.size());
if (len == HEARTBEAT.size()) {
std::cout << "Received heartbeat, responding..." << std::endl;
send_heartbeat(socket); // 发送回应
} else {
std::cerr << "Invalid heartbeat received." << std::endl;
}
}
int main() {
try {
boost::asio::io_context io;
tcp::resolver resolver(io);
tcp::resolver::results_type endpoints = resolver.resolve("localhost", "8080");
for (auto endpoint : endpoints) {
tcp::socket socket(io);
boost::asio::connect(socket, endpoint);
std::cout << "Connected to server at " << endpoint.address() << ':' << endpoint.port() << std::endl;
send_heartbeat(socket); // 发送初始心跳包
handle_heartbeat(socket); // 开始处理心跳循环
}
io.run();
}
catch (std::exception& e) {
std::cerr << "Error: " << e.what() << std::endl;
}
return 0;
}
```
阅读全文