boost socket通讯实例

server.cpp

#include <iostream>
#include <boost/asio.hpp>
using namespace boost::asio;
int main()
try {
    io_service ios;
    ip::address addr;
    addr = addr.from_string("127.0.0.1");
    std::cout << "server starting." << std::endl;
    ip::tcp::acceptor acceptor(ios, ip::tcp::endpoint(addr, 6688));
    std::cout << acceptor.local_endpoint().address() << ":" << acceptor.local_endpoint().port() << std::endl;
    while (true) {
        std::cout<<"socket wait"<<std::endl;
        ip::tcp::socket sock(ios);
        acceptor.accept(sock);
        std::cout << "client: " << sock.remote_endpoint().address()<<":" <<sock.remote_endpoint().port()<< std::endl;
        sock.write_some(buffer("hello asio"));
    }
    
} catch (std::exception& e) {
    std::cout << e.what() << std::endl;
}


client.cpp

#include <iostream>
#include <boost/ref.hpp>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/function.hpp>
using namespace boost::asio;
using namespace std;
void client(io_service &ios)
try {
    std::cout << "client starting." << std::endl;
    ip::tcp::socket sock(ios);
    ip::address adr = ip::address::from_string("127.0.0.1");
    std::cout << adr.to_string() << std::endl;
    ip::tcp::endpoint ep(adr, 6688);
    sock.connect(ep);
    std::vector<char> str(100, 0);
    sock.read_some(buffer(str));
    std::cout << "receive from: " << sock.remote_endpoint().address() << std::endl;
    std::cout << &str[0] << std::endl;
} catch (std::exception &e) {
    std::cout << e.what() << std::endl;
}
class a_timer {
private:
    int count, count_max;
    boost::function<void() > f;
    boost::asio::deadline_timer timer;
public:

    template<typename F>
    a_timer(io_service &ios, int x, F func) : f(func), count_max(x), count(0),
    timer(ios, boost::posix_time::millisec(500)) {
        timer.async_wait(boost::bind(&a_timer::call_func, this, boost::asio::placeholders::error));
    }

    void call_func(const boost::system::error_code&) {
        if (count >= count_max) {
            return;
        }
        ++count;
        f();
        timer.expires_at(timer.expires_at() + boost::posix_time::millisec(500));
        timer.async_wait(boost::bind(&a_timer::call_func, this, boost::asio::placeholders::error));
    }
};
int main() {
    io_service ios;
    //自定义定时器5次执行client()函数
    a_timer at(ios, 5, boost::bind(client, boost::ref(ios)));
    ios.run();
}


评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值