【问题标题】:UDP communication using c++ boost asio使用c ++ boost asio的UDP通信
【发布时间】:2017-10-31 14:22:43
【问题描述】:

我需要通过 UDP 与专用网络中的其他设备通信。我是使用 boost 的新手,但根据我在网上搜索的内容以及 Boost 网站上的教程,我想出了以下代码。我目前正在尝试从我自己的设备发送和接收数据。只是为了单元测试和最终确定代码。

问题:我无法收到任何消息。我错过了什么?

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <string>
#include "boost/asio.hpp"
#include <thread>
#include <boost/array.hpp>
#include <boost/bind.hpp>

#define SRVR_UDP_PORT  10251
#define CLNT_UDP_PORT 10252

boost::array<char, 1024> recv_buffer;

void Sender(std::string in)
{
    boost::asio::io_service io_service;
    boost::asio::ip::udp::socket socket(io_service);
    boost::asio::ip::udp::endpoint remote_endpoint;
    socket.open(boost::asio::ip::udp::v4());
    remote_endpoint = boost::asio::ip::udp::endpoint(boost::asio::ip::address::from_string("192.168.1.64"), SRVR_UDP_PORT);

    boost::system::error_code err;
    socket.send_to(boost::asio::buffer(in.c_str(), in.size()), remote_endpoint, 0, err);
    socket.close();
    //int i =0;
    printf("Sending Payload --- \n");
}

void handle_receive(const boost::system::error_code& error, size_t bytes_transferred)
{
    std::cout << "Received: '" << std::string(recv_buffer.begin(), recv_buffer.begin()+bytes_transferred) << "'\n";
}


void Receiver()
{
    while(1)
    {
        boost::asio::io_service io_service;
        boost::asio::ip::udp::socket socket(io_service);
        boost::asio::ip::udp::endpoint remote_endpoint;

        //socket.open(boost::asio::ip::udp::v4());
        boost::system::error_code err;
        remote_endpoint = boost::asio::ip::udp::endpoint(boost::asio::ip::address::from_string("192.168.1.64"), CLNT_UDP_PORT);

        socket.open(boost::asio::ip::udp::v4());
        //https://stackoverflow.com/questions/26820215/boost-asio-udp-client-async-receive-from-calls-handler-even-when-there-are-no-in
        socket.async_receive_from(boost::asio::buffer(recv_buffer),
                                    remote_endpoint,
                                    boost::bind(handle_receive,
                                    boost::asio::placeholders::error,
                                    boost::asio::placeholders::bytes_transferred));                                    
                                    //socket.close();
    }
    int i = 0;
    printf("Received Payload --- %d", i);

}

int main(int argc, char *argv[])
{
    //std::thread s(Sender);
    std::thread r(Receiver);
    //s.join();
    std::string input = argv[1];
    printf("Input is %s\nSending it to Sender Function...\n", input.c_str());
    Sender(input);
    r.join();
    return 0;
}

【问题讨论】:

    标签: c++ sockets boost udp boost-asio


    【解决方案1】:

    你忘了

    1. 绑定接收套接字
    2. 运行io_service
    3. 为接收方使用相同的 UDP 端口

    在循环中执行async_* 调用是没有用的,因为它所做的只是队列任务,除非线程运行io_service::run,否则这些任务不会被执行。

    Live On Coliru

    #include <boost/asio.hpp>
    #include <boost/array.hpp>
    #include <boost/bind.hpp>
    #include <thread>
    #include <iostream>
    
    #define IPADDRESS "127.0.0.1" // "192.168.1.64"
    #define UDP_PORT 13251
    
    using boost::asio::ip::udp;
    using boost::asio::ip::address;
    
    void Sender(std::string in) {
        boost::asio::io_service io_service;
        udp::socket socket(io_service);
        udp::endpoint remote_endpoint = udp::endpoint(address::from_string(IPADDRESS), UDP_PORT);
        socket.open(udp::v4());
    
        boost::system::error_code err;
        auto sent = socket.send_to(boost::asio::buffer(in), remote_endpoint, 0, err);
        socket.close();
        std::cout << "Sent Payload --- " << sent << "\n";
    }
    
    struct Client {
        boost::asio::io_service io_service;
        udp::socket socket{io_service};
        boost::array<char, 1024> recv_buffer;
        udp::endpoint remote_endpoint;
    
        int count = 3;
    
        void handle_receive(const boost::system::error_code& error, size_t bytes_transferred) {
            if (error) {
                std::cout << "Receive failed: " << error.message() << "\n";
                return;
            }
            std::cout << "Received: '" << std::string(recv_buffer.begin(), recv_buffer.begin()+bytes_transferred) << "' (" << error.message() << ")\n";
    
            if (--count > 0) {
                std::cout << "Count: " << count << "\n";
                wait();
            }
        }
    
        void wait() {
            socket.async_receive_from(boost::asio::buffer(recv_buffer),
                remote_endpoint,
                boost::bind(&Client::handle_receive, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred));
        }
    
        void Receiver()
        {
            socket.open(udp::v4());
            socket.bind(udp::endpoint(address::from_string(IPADDRESS), UDP_PORT));
    
            wait();
    
            std::cout << "Receiving\n";
            io_service.run();
            std::cout << "Receiver exit\n";
        }
    };
    
    int main(int argc, char *argv[])
    {
        Client client;
        std::thread r([&] { client.Receiver(); });
    
        std::string input = argc>1? argv[1] : "hello world";
        std::cout << "Input is '" << input.c_str() << "'\nSending it to Sender Function...\n";
    
        for (int i = 0; i < 3; ++i) {
            std::this_thread::sleep_for(std::chrono::milliseconds(200));
            Sender(input);
        }
    
        r.join();
    }
    

    打印

    Input is 'hello'
    Sending it to Sender Function...
    Receiving
    Sent Payload --- 5
    Received: 'hello' (Success)
    Count: 2
    Sent Payload --- 5
    Received: 'hello' (Success)
    Count: 1
    Sent Payload --- 5
    Received: 'hello' (Success)
    Receiver exit
    

    【讨论】:

    • 初学者问题 io_service.run();命令未运行,因为它在等待语句之后。它仅在函数退出之前执行。为什么甚至需要它?
    • 我已经解释过了。文档也是如此:at the bottom 和例如第一个异步教程步骤boost.org/doc/libs/1_64_0/doc/html/boost_asio/tutorial/…。关键是,即使您命名函数wait,它根本不会等待。因为那不是async
    • 我们可以避免绑定到特定的端口或IP,在我们收到数据包后,检查端点的端口/ip_address吗?我们可以创建一个套接字来监听所有端口的任何 ipv4 地址吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多