现在的位置: 首页 > 综合 > 正文

boost asio库 同步socket连接示例

2018年06月06日 ⁄ 综合 ⁄ 共 1140字 ⁄ 字号 评论关闭
<pre name="code" class="cpp">///////////////////////////////////////
//  Asio同步socket连接示例
//
#include <iostream>
#include <boost/thread.hpp>
#include <boost/asio/io_service.hpp>
#include <boost/asio.hpp>
using namespace boost;
typedef boost::asio::io_service IoService;
typedef boost::asio::ip::tcp TCP;
bool flag=true;

void client()  
{
    int i=0;
    while(i++<10)
    {
        this_thread::sleep(posix_time::seconds(1)); //延时函数
        try
        {
        IoService ios;
        TCP::socket so(ios);
        TCP::endpoint ep(asio::ip::address::from_string("127.0.0.1"),9999); //绑定对方的ip和端口
        so.connect(ep);
        char str[100]={0};
        so.read_some(asio::buffer(str)); //接收服务器端送回的消息
        std::cout<<"client: read from ser:"<<str<<std::endl;

        }
        catch(std::exception&e)
        {
            std::cout<<e.what()<<std::endl;
        }
    }
    flag=false;
}

int main()
{
try
{
    IoService ios;
    TCP::acceptor my_acceptor(ios,TCP::endpoint(TCP::v4(),9999));  //服务器段绑定协议和端口
    std::cout<<my_acceptor.local_endpoint().address()<<std::endl;

    thread tc(&client);  //开一个线程执行客户端
    while(flag) //服务器端循环接收客户端socket
    {
        std::cout<<"waiting for client..."<<std::endl;
        TCP::socket mysocket(ios);
        my_acceptor.accept(mysocket);  
        mysocket.write_some(asio::buffer("hahahahah")); //向客户端写数据
    }
    tc.join();
}
catch(std::exception&e)
{
    std::cout<<e.what()<<std::endl;
}
    return 0;
}

【上篇】
【下篇】

抱歉!评论已关闭.