定时发送心跳包用C++代码举例
时间: 2023-07-11 07:47:21 浏览: 46
以下是一个简单的C++代码示例,用于发送心跳包:
```c++
#include <iostream>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>
#include <thread>
#include <chrono>
using namespace std;
void sendHeartbeat(int sockfd, sockaddr_in serverAddr) {
char buffer[1024] = "heartbeat";
while (true) {
int sendResult = sendto(sockfd, buffer, strlen(buffer), 0, (struct sockaddr *) &serverAddr, sizeof(serverAddr));
if (sendResult < 0) {
cout << "Failed to send heartbeat!" << endl;
} else {
cout << "Heartbeat sent successfully!" << endl;
}
std::this_thread::sleep_for(std::chrono::seconds(10));
}
}
int main(int argc, char **argv) {
int sockfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (sockfd < 0) {
cout << "Failed to create socket!" << endl;
return -1;
}
struct sockaddr_in serverAddr;
memset(&serverAddr, 0, sizeof(serverAddr));
serverAddr.sin_family = AF_INET;
serverAddr.sin_addr.s_addr = inet_addr("127.0.0.1"); // 服务器IP地址
serverAddr.sin_port = htons(8888); // 服务器端口号
std::thread heartBeatThread(sendHeartbeat, sockfd, serverAddr);
heartBeatThread.join();
close(sockfd);
return 0;
}
```
该代码创建了一个UDP socket,然后使用一个独立的线程发送心跳包到指定的服务器IP地址和端口。在发送心跳包之前,线程会暂停10秒钟。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)