boost::asio 同步UDP网络编程(客户端和服务端)

最近在寻找一种跨平台的socket编程库,最初找到的是curl,使用比较简单,但是用起来不是那么容易理解,curl功能比较强大,封装了很多通信协议,例如TCP, UDP, HTTP等。

后来无意中发现boost,然后网上找到他的中文手册,大概浏览下了,嗯。。,这就是我想要的,轻巧,跨平台,支持C++11标准,按照网上标准教程进行安装,我的平台是ubuntu16.04,安装后头文件目录:/usr/local/include/boost,lib库文件目录:/usr/local/lib.

不说了,先上栗子,新手记得慢点吃:)

一、UDP 客户端

#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>

#include <iostream>

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 us " << msg << ": "<< (copy == msg ? "OK" : "FAIL") << std::endl;

    sock.close();

}

int main(int argc, char* argv[]) {

    char* messages[] = { "I", "love", "beautiful" , "girl" , 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");

}

编译命令:

g++ UdpClient.cpp -o UdpClient -I /usr/local/include/boost/ -L /usr/local/lib -lboost_thread -lpthread


二、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>

#include <iostream>

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);

std::cout<<msg<<std::endl;

    }

}

int main(int argc, char* argv[]) {

    handle_connections();

}

编译命令:

g++ UdpServer.cpp -o UdpSever -I /usr/local/include/boost/ -L /usr/local/lib -lpthread

三、运行结果

记得点赞。

猜你喜欢

转载自blog.csdn.net/jiaken2660/article/details/100156417