boost::asio编程-同步UDP

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.youkuaiyun.com/anda0109/article/details/41981799

同步UDP比较简单,直接看例子:

#include "stdafx.h"  
#include "boost/asio.hpp"  
#include "boost/shared_ptr.hpp"  
#include "boost/thread.hpp"  
#include <boost/lexical_cast.hpp>//使用字符串转换功能  

using namespace std;  
using namespace boost::asio;  

#ifdef _MSC_VER  
#define _WIN32_WINNT    0X0501  //避免VC下编译警告  
#endif  

int udp_server()  
{  
    io_service ios;  
    ip::udp::endpoint server_ep(ip::udp::v4(),PORT);  
    ip::udp::socket sock(ios,server_ep);  
    while(true)  
    {  
        char buf[1024];  
        boost::system::error_code ec;  
        ip::udp::endpoint remote_ep;//接收远程连接进来的端点  
        sock.receive_from(buffer(buf),remote_ep,0,ec);  
        if(ec && ec!=error::message_size)  
        {  
            throw boost::system::system_error(ec);  
        }  
        cout<<"receive from remote ip:"<<remote_ep.address()<<endl;  
        cout<<"receive from remote port:"<<remote_ep.port()<<endl;  
        sock.send_to(buffer("I heard you!"),remote_ep);  
    }  
    return 0;  
}  

int udp_client()  
{  
    io_service ios;  
    //要发往的服务端点  
    ip::udp::endpoint send_ep(ip::address::from_string("127.0.0.1"),PORT);  
    ip::udp::socket sock(ios);  
    sock.open(ip::udp::v4());  
    //向服务端发送数据  
    sock.send_to(buffer("hello"),send_ep);  

    //接收数据  
    vector<char> v(1024,0);  
    ip::udp::endpoint ep;  
    sock.receive_from(buffer(v),ep);  
    cout<<"receive from ip:"<<ep.address()<<endl;  
    cout<<"receive msg:"<<&v[0]<<endl;  
}  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值