【发布时间】:2020-12-18 11:37:09
【问题描述】:
这是接收数据并打印数据的 UDP 服务器的代码。
我能够收到消息,但在消息的末尾我也会收到一些垃圾字符。
我只想显示实际发送的消息,最后没有垃圾字符。
/////////////////////////////////////// ///////////////////////////////////////// //////////////////////
#pragma once
#include <string>
#include <iostream>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/array.hpp>
#include <qdebug.h>
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))
{
start_receive();
}
private:
void start_receive()
{
socket_.async_receive_from(
boost::asio::buffer(recv_buffer_), remote_endpoint_,
boost::bind(&udp_server::handle_receive, this,
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred));
}
void handle_receive(const boost::system::error_code& error,
std::size_t /*bytes_transferred*/)
{
if (!error || error == boost::asio::error::message_size)
{
std::string str(recv_buffer_.c_array());
std::cout << str; // Printing the string shows junk characters also
boost::shared_ptr<std::string> message(
new std::string("WAVEFRONT"));
socket_.async_send_to(boost::asio::buffer(*message), remote_endpoint_,
boost::bind(&udp_server::handle_send, this, message,
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred));
start_receive();
}
}
void handle_send(boost::shared_ptr<std::string> /*message*/,
const boost::system::error_code& /*error*/,
std::size_t /*bytes_transferred*/)
{
}
udp::socket socket_;
udp::endpoint remote_endpoint_;
boost::array< char, 256> recv_buffer_;
};
【问题讨论】:
标签: boost udp boost-asio