我正在尝试创建简单的UDP服务器,所以我修改了一个白天的例子。基本上,我想发送一个数据包并从设备接收响应,直接通过电缆连接。问题是,我可以看到通过Wireshark发送和接收的数据包,但我的程序没有看到传入的数据包。
另外我想提一下,我的有效载荷数据是9-10个字节,因为我很担心是否应该添加一些填充。任何帮助将不胜感激。
#include <iostream>
#include <boost/array.hpp>
#include <boost/bind.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/asio.hpp>
using boost::asio::ip::udp;
class udp_server {
public:
udp_server(boost::asio::io_service& io_service) : socket_(io_service, , udp::endpoint(udp::v4(), 13)) {
send_buf = { 0xEF, 0x02, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00 };
receiver_endpoint_ = udp::endpoint(boost::asio::ip::address_v4::broadcast(), 8888);
socket_.set_option(boost::asio::socket_base::broadcast(true));
socket_.set_option(boost::asio::ip::udp::socket::reuse_address(true));
start_send();
}
private:
void start_receive() {
socket_.async_receive_from(
boost::asio::buffer(recv_buffer_), sender_endpoint_,
boost::bind(&udp_server::handle_receive, this,
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred));
}
void start_send() {
rand_buf();
socket_.async_send_to(boost::asio::buffer(send_buf), receiver_endpoint_,
boost::bind(&udp_server::handle_send, this, send_buf,
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred));
}
void handle_receive(const boost::system::error_code& error,
std::size_t b/*bytes_transferred*/) {
if (!error || error == boost::asio::error::message_size) {
std::cout << "rcv: " << b << "\n";
start_send();
}
}
void handle_send(boost::array<unsigned char, 9>& /*message*/,
const boost::system::error_code& /*error*/,
std::size_t b/*bytes_transferred*/) {
std::cout << "snt: " << b << "\n";
start_receive();
}
void rand_buf() {
// randomize last 4 bytes
send_buf[5] = rand() % 0xFF;
send_buf[6] = rand() % 0xFF;
send_buf[7] = rand() % 0xFF;
send_buf[8] = rand() % 0xFF;
}
udp::socket socket_;
udp::endpoint receiver_endpoint_;
udp::endpoint sender_endpoint_;
boost::array<char, 64> recv_buffer_;
boost::array<unsigned char, 9> send_buf;
};
int main() {
try {
boost::asio::io_service io_service;
udp_server server(io_service);
io_service.run();
} catch (std::exception& e) {
std::cerr << e.what() << std::endl;
}
return 0;
}
编辑:如果我自己解决了。问题是,我忘了添加端口来在构造函数中的socket_中侦听