在C++中进行UDP通信的方式主要有两种:
示例代码如下:
#include <iostream>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
int main() {
int socket_fd;
struct sockaddr_in server_addr, client_addr;
char buffer[1024];
// 创建UDP套接字
socket_fd = socket(AF_INET, SOCK_DGRAM, 0);
if (socket_fd < 0) {
std::cerr << "Failed to create socket" << std::endl;
return -1;
}
// 绑定本地IP地址和端口号
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = INADDR_ANY;
server_addr.sin_port = htons(12345);
if (bind(socket_fd, (struct sockaddr*)&server_addr, sizeof(server_addr)) < 0) {
std::cerr << "Failed to bind socket" << std::endl;
return -1;
}
// 接收数据包
socklen_t client_addr_len = sizeof(client_addr);
ssize_t recv_len = recvfrom(socket_fd, buffer, sizeof(buffer), 0, (struct sockaddr*)&client_addr, &client_addr_len);
if (recv_len < 0) {
std::cerr << "Failed to receive data" << std::endl;
return -1;
}
buffer[recv_len] = '\0';
std::cout << "Received message: " << buffer << std::endl;
close(socket_fd);
return 0;
}
示例代码如下:
#include <iostream>
#include <boost/asio.hpp>
int main() {
boost::asio::io_context io_context;
boost::asio::ip::udp::socket socket(io_context, boost::asio::ip::udp::endpoint(boost::asio::ip::udp::v4(), 12345));
char buffer[1024];
boost::asio::ip::udp::endpoint remote_endpoint;
boost::system::error_code error;
// 接收数据包
size_t recv_len = socket.receive_from(boost::asio::buffer(buffer), remote_endpoint, 0, error);
if (error) {
std::cerr << "Failed to receive data: " << error.message() << std::endl;
return -1;
}
buffer[recv_len] = '\0';
std::cout << "Received message: " << buffer << std::endl;
return 0;
}
以上是两种常用的C++中进行UDP通信的方式。具体选择哪种方式取决于使用者的需求和偏好。