【问题标题】:How to Read data from boost UDP server如何从 boost UDP 服务器读取数据
【发布时间】: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


    【解决方案1】:

    “最后的垃圾字符”是recv_buffer_ 中的字符asio 收到的 UDP 数据。

    您在handle_receive 函数中注释掉的bytes_transferred 参数告诉您asio 实际收到了多少个字符,即recv_buffer_.size()。

    如果您只是将bytes_transferred 字符复制到str,您将看到收到的内容没有“到底是垃圾字符”。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-14
      • 2018-06-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多