LinuxC/C++编程基础(15) boost同步socket处理

来源:互联网 发布:浪费水资源的数据 编辑:程序博客网 时间:2024/05/16 14:44

一.服务器端server.cpp的实现,如下:

#include <iostream>
#include <boost/asio.hpp>
using namespace boost::asio;
int main(int argc,char** argv){
    try{
        std::cout<<"serverstart."<<std::endl;
        io_service ios;
        ip::tcp::acceptor acceptor(ios,ip::tcp::endpoint(ip::tcp::v4(),9999));
       std::cout<<acceptor.local_endpoint().address()<<std::endl;
        while(true){
            ip::tcp::socketsock(ios);
            acceptor.accept(sock);
           std::cout<<"client:";
            std::cout<<sock.remote_endpoint().address()<<std::endl;
           sock.write_some(buffer("hello asio"));
        }
    }catch(std::exception& e){
       std::cout<<e.what()<<std::endl;
    }
    return 0;
}

二.客户端client.cpp的实现,如下:

#include <iostream>
#include <vector>
#include <boost/ref.hpp>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/function.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
using namespace boost;
using namespace boost::asio;

class a_timer{
private:
    int count;
    int count_max;
    function<void()> f;
    deadline_timer t;
public:
    template<typename F>
    a_timer(io_service& ios,int x,Ffunc):f(func),count_max(x),count(0)
        ,t(ios,posix_time::millisec(500))
    {
       t.async_wait(bind(&a_timer::call_func,this,placeholders::error));
    }
    void call_func(const system::error_code& e){
        if(count >= count_max){
            return;
        }
        ++count;
        f();
        t.expires_at(t.expires_at() +posix_time::millisec(500));
       t.async_wait(bind(&a_timer::call_func,this,placeholders::error));
    }
};
void client(io_service& ios){
    try{
        std::cout<<"clientstart."<<std::endl;
        ip::tcp::socket sock(ios);
        ip::tcp::endpointep(ip::address::from_string("127.0.0.1"),9999);
        sock.connect(ep);
        std::vector<char> str(100,0);
        sock.read_some(buffer(str));
        std::cout<<"receive from"<<sock.remote_endpoint().address();
        std::cout<<""<<&str[0]<<std::endl;
    }catch(std::exception& e){
       std::cout<<e.what()<<std::endl;
    }
}
int main(int argc,char** argv){
    io_service ios;
    a_timer at(ios,5,bind(client,ref(ios)));
    ios.run();
    return 0;
}

三.运行结果,如下:

服务器端:

 

客户端:



参考文献:boost库完全开发指南,罗剑锋 著

转载请注明出处:山水间博客:http://blog.csdn.net/linyanwen99/article/details/8254966


原创粉丝点击