编写一个以sendot和recvfrom函数的非连接UDP通信程序,发送端发送消息finish退出通讯的完整C++代码
时间: 2024-11-03 07:13:02 浏览: 10
C/C++ 发送UDP数据与接收UDP数据完整代码(支持指定网卡)
在C++中,你可以使用`boost::asio`库来编写一个非连接的UDP通信程序,因为标准库`std::socket`并不直接支持`sendto`和`recvfrom`这两个功能。以下是一个简单的示例,展示了如何创建一个发送端(sender)和接收端(receiver)的UDP通信:
首先,确保已安装并包含了Boost.Asio库,然后按照下面的代码结构进行:
```cpp
#include <iostream>
#include <boost/asio.hpp>
#include <string>
// 发送部分
class UDPSender {
public:
UDPSender(boost::asio::ip::udp::endpoint endpoint)
: socket_(io_service_)
, endpoint_(endpoint) {}
void send(const std::string& message) {
boost::asio::write(socket_, boost::asio::buffer(message + " finish"));
}
private:
boost::asio::io_service io_service_;
boost::asio::ip::udp::socket socket_;
boost::asio::ip::udp::endpoint endpoint_;
};
// 接收部分
class UDPReceiver {
public:
UDPReceiver(boost::asio::io_service& io_service)
: socket_(io_service) {}
void start() {
boost::asio::async_read(socket_,
boost::asio::buffer(buffer_, MAX_PACKET_SIZE),
[this](auto error, auto bytes_transferred) {
if (!error && bytes_transferred > 0) {
std::string received_message(buffer_.data(), bytes_transferred);
processMessage(received_message);
}
// 如果接收到"finish",结束接收
if (received_message == "finish") {
socket_.close();
} else {
receive();
}
});
}
private:
void processMessage(const std::string& message) {
std::cout << "Received: " << message << std::endl;
}
void receive() {
socket_.async_read_some(
boost::asio::buffer(buffer_, MAX_PACKET_SIZE),
std::bind(&UDPReceiver::start, this));
}
boost::array<char, MAX_PACKET_SIZE> buffer_;
boost::asio::ip::udp::socket socket_;
};
int main() {
try {
boost::asio::io_service io_service;
// 创建并配置发送端点
boost::asio::ip::address sender_address = ...; // 你的IP地址
boost::asio::ip::port_number sender_port = ...; // 你的端口
boost::asio::ip::udp::endpoint sender_endpoint(sender_address, sender_port);
// 创建并启动发送器
UDPSender sender(sender_endpoint);
sender.send("Hello, UDP!");
// 创建并启动接收器
UDPReceiver receiver(io_service);
receiver.start();
io_service.run(); // 运行IO服务,直到接收结束
} catch (const std::exception& e) {
std::cerr << "Error: " << e.what() << std::endl;
}
return 0;
}
```
阅读全文