菜鸟笔记
提升您的技术认知

Boost.Asio C++ 网络编程之六:UDP回显客户端/服务

阅读 : 43

       因为UDP不能保证所有消息都抵达接收者,所以不能保证消息都以回车结尾。

       在服务端,收到消息后,简单的回发给客户端,并且不关闭socket,因为这是UDP。

一.UDP同步客户端

UDP客户端比TCP客户端要简单:

#ifdef WIN32
#define _WIN32_WINNT 0x0501
#include <stdio.h>
#endif

#include <boost/thread.hpp>
#include <boost/bind.hpp>
#include <boost/asio.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/enable_shared_from_this.hpp>
using namespace boost::asio;
io_service service;

ip::udp::endpoint ep(ip::address::from_string("127.0.0.1"), 8001);

void sync_echo(std::string msg) {
    ip::udp::socket sock(service, ip::udp::endpoint(ip::udp::v4(), 0));
    sock.send_to(buffer(msg), ep);
    char buff[1024];
    ip::udp::endpoint sender_ep;
    int bytes = sock.receive_from(buffer(buff), sender_ep);
    std::string copy(buff, bytes);
    std::cout << "server echoed our " << msg << ": "
        << (copy == msg ? "OK" : "FAIL") << std::endl;
    sock.close();
}

int main(int argc, char* argv[]) {
    char* messages[] = { "Can", "ge", "ge" , "blog" , 0 };
    boost::thread_group threads;
    for (char ** message = messages; *message; ++message) {
        threads.create_thread(boost::bind(sync_echo, *message));
        boost::this_thread::sleep(boost::posix_time::millisec(100));
    }
    threads.join_all();
    system("pause");
}

二.UDP同步服务端
UDP服务端会是你写过的最简单的服务端:

#ifdef WIN32
#define _WIN32_WINNT 0x0501
#include <stdio.h>
#endif

#include <boost/bind.hpp>
#include <boost/asio.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/enable_shared_from_this.hpp>
using namespace boost::asio;
using namespace boost::posix_time;
io_service service;
void handle_connections() {
    char buff[1024];
    ip::udp::socket sock(service, ip::udp::endpoint(ip::udp::v4(), 8001));
    while (true) {
        ip::udp::endpoint sender_ep;
        int bytes = sock.receive_from(buffer(buff), sender_ep);
        std::string msg(buff, bytes);
        sock.send_to(buffer(msg), sender_ep);
    }
}

int main(int argc, char* argv[]) {
    handle_connections();
}</code></pre> 下面是客户端回显的结果,当然要先启动服务端。 
<p style="text-align:justify"><img src="https://static.coonote.com/2021/12/7106881665834187682.png" class="aligncenter"><br></p> 
<p><strong>三.UDP异步客户端</strong></p> 
<pre><code>#ifdef WIN32  
#define _WIN32_WINNT 0x0501  
#include <stdio.h>  
#endif  

#include <boost/thread.hpp>  
#include <boost/bind.hpp>  
#include <boost/asio.hpp>  
#include <boost/shared_ptr.hpp>  
#include <boost/enable_shared_from_this.hpp>  
using namespace boost::asio;
io_service service;
ip::udp::endpoint ep(ip::address::from_string("127.0.0.1"), 8001);


#define MEM_FN(x)       boost::bind(&self_type::x, shared_from_this())  
#define MEM_FN1(x,y)    boost::bind(&self_type::x, shared_from_this(),y)  
#define MEM_FN2(x,y,z)  boost::bind(&self_type::x, shared_from_this(),y,z)  


class talk_to_svr : public boost::enable_shared_from_this<talk_to_svr>
    , boost::noncopyable {
    typedef talk_to_svr self_type;
    talk_to_svr(const std::string & message)
        : sock_(service, ip::udp::endpoint(ip::udp::v4(), 0)), started_(true), message_(message) {}
    void start() {
        do_write(message_);
    }
public:
    typedef boost::system::error_code error_code;
    typedef boost::shared_ptr<talk_to_svr> ptr;


    static ptr start(const std::string & message) {
        ptr new_(new talk_to_svr(message));
        new_->start();
        return new_;
    }
    bool started() { return started_; }
private:
    void on_read(const error_code & err, size_t bytes) {
        if (!err) {
            std::string copy(read_buffer_, bytes);
            std::cout << "server echoed our " << message_ << ": "
                << (copy == message_ ? "OK" : "FAIL") << std::endl;
        }
    }
    void on_write(const error_code & err, size_t bytes) {
        do_read();
    }
    void do_read() {
        sock_.async_receive_from(buffer(read_buffer_), sender_ep,
            MEM_FN2(on_read, _1, _2));
    }
    void do_write(const std::string & msg) {
        std::copy(msg.begin(), msg.end(), write_buffer_);
        sock_.async_send_to(buffer(write_buffer_, msg.size()), ep,
            MEM_FN2(on_write, _1, _2));
    }


private:
    ip::udp::socket sock_;
    ip::udp::endpoint sender_ep;
    enum { max_msg = 1024 };
    char read_buffer_[max_msg];
    char write_buffer_[max_msg];
    bool started_;
    std::string message_;
};


int main(int argc, char* argv[]) {
    char* messages[] = { "Can", "ge", "ge", "blog", 0 };
    for (char ** message = messages; *message; ++message) {
        talk_to_svr::start(*message);
        boost::this_thread::sleep(boost::posix_time::millisec(100));
    }
    service.run();
    system("pause");
}

四.UDP异步服务器

#ifdef WIN32
#define _WIN32_WINNT 0x0501
#include <stdio.h>
#endif

#include <boost/bind.hpp>
#include <boost/asio.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/enable_shared_from_this.hpp>
using namespace boost::asio;
using namespace boost::posix_time;
io_service service;

#define MEM_FN(x)       boost::bind(&self_type::x, shared_from_this())  
#define MEM_FN1(x,y)    boost::bind(&self_type::x, shared_from_this(),y)  
#define MEM_FN2(x,y,z)  boost::bind(&self_type::x, shared_from_this(),y,z)  

class talk_to_client : public boost::enable_shared_from_this<talk_to_client>, boost::noncopyable {
    typedef talk_to_client self_type;
    talk_to_client() : sock_(service, ip::udp::endpoint(ip::udp::v4(), 8001)), started_(false) {}
public:
    typedef boost::system::error_code error_code;
    typedef boost::shared_ptr<talk_to_client> ptr;

    void start() {
        started_ = true;
        do_read();
    }
    static ptr new_() {
        ptr new_(new talk_to_client);
        return new_;
    }
    ip::udp::socket & sock() { return sock_; }
private:
    void on_read(const error_code & err, size_t bytes) {
        if (!err) {
            std::string msg(read_buffer_, bytes);
            do_write(msg);
        }
    }

    void on_write(const error_code & err, size_t bytes) {
        do_read();
    }
    void do_read() {
        sock_.async_receive_from(buffer(read_buffer_), sender_ep,
            MEM_FN2(on_read, _1, _2));
    }
    void do_write(const std::string & msg) {
        std::copy(msg.begin(), msg.end(), write_buffer_);
        sock_.async_send_to(buffer(write_buffer_, msg.size()), sender_ep,
            MEM_FN2(on_write, _1, _2));
    }

private:
    ip::udp::socket sock_;
    ip::udp::endpoint sender_ep;
    enum { max_msg = 1024 };
    char read_buffer_[max_msg];
    char write_buffer_[max_msg];
    bool started_;
};

int main(int argc, char* argv[]) {
    talk_to_client::ptr client = talk_to_client::new_();
    client->start();
    service.run();
}

客户端回显结果和同步时一样,如下: