目录
1 send.cpp
2 receive.cpp
3 编译运行
4 测试
1 send.cpp
#include <iostream>
#include <string>
#include <cstring>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h> // 添加这个头文件
#include <thread>
void sendData() {
int sockfd;
struct sockaddr_in serverAddr;
// 创建UDP socket
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if (sockfd < 0) {
std::cerr << "Failed to create socket" << std::endl;
return;
}
// 设置服务器地址和端口
serverAddr.sin_family = AF_INET;
serverAddr.sin_port = htons(12345);
serverAddr.sin_addr.s_addr = inet_addr("127.0.0.1");
while (true) {
// 发送数据
std::string message = "Hello, UDP!";
sendto(sockfd, message.c_str(), message.length(), 0, (struct sockaddr*)&serverAddr, sizeof(serverAddr));
std::cout << "Sent: " << message << std::endl;
sleep(1); // 每秒发送一次
}
close(sockfd);
}
int main() {
std::thread sender(sendData);
sender.join(); // 等待发送线程结束
return 0;
}
2 receive.cpp
#include <iostream>
#include <string>
#include <cstring>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <thread>
void receiveData() {
int sockfd;
struct sockaddr_in serverAddr, clientAddr;
socklen_t addrLen = sizeof(clientAddr);
char buffer[1024];
// 创建UDP socket
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if (sockfd < 0) {
std::cerr << "Failed to create socket" << std::endl;
return;
}
// 设置服务器地址和端口
serverAddr.sin_family = AF_INET;
serverAddr.sin_port = htons(12345);
serverAddr.sin_addr.s_addr = INADDR_ANY;
// 绑定地址和端口
bind(sockfd, (struct sockaddr*)&serverAddr, sizeof(serverAddr));
while (true) {
// 接收数据
int bytesReceived = recvfrom(sockfd, buffer, 1024, 0, (struct sockaddr*)&clientAddr, &addrLen);
buffer[bytesReceived] = '\0';
std::cout << "Received: " << buffer << std::endl;
}
close(sockfd);
}
int main() {
std::thread receiver(receiveData);
receiver.join(); // 等待接收线程结束
return 0;
}
3 编译运行
g++ -o receive_test receive.cpp -lpthread
g++ -o send_test send.cpp -lpthread
4 测试
直接把板子连接到我家的电视上,
参考文献:C++怎么实现udp发送和接收-开发者知识库平台 - 辰迅云