boost asio同步和异步socket

创建时间:2023-04-27 14:57:40
栏目:c++

同步客户端

// 同步客户端 
#include <boost/asio.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/bind.hpp>
#include <iostream>

#if defined(_WIN32) || defined(__WIN32__) || defined(WIN32)
    #include <winsock2.h>
    #pragma comment(lib,"ws2_32.lib")  
#endif

using namespace boost::asio;

int main(){
    io_service iosev; 
    ip::tcp::socket socket(iosev);
    ip::tcp::endpoint ep(ip::address_v4::from_string("127.0.0.1"), 1000);

    boost::system::error_code ec; 
    socket.connect(ep, ec);
    if(ec){
        std::cout<<boost::system::system_error(ec).what()<<std::endl; 
        return -1; 
    }

    while(true){
        char buf[100];
        size_t len = socket.read_some(buffer(buf), ec);
        std::cout.write(buf, len);
    }


    return 0;
}

同步服务端

// 同步服务端 
#include <boost/asio.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/bind.hpp>
#include <iostream>

#if defined(_WIN32) || defined(__WIN32__) || defined(WIN32)
    #include <winsock2.h>
    #pragma comment(lib,"ws2_32.lib")  

#endif

using namespace boost::asio;
int main(){

    io_service iosev; 
    ip::tcp::acceptor acceptor(iosev, ip::tcp::endpoint(ip::tcp::v4(), 1000));
    for(;;){
        ip::tcp::socket socket(iosev);
        acceptor.accept(socket);
        std::cout<<socket.remote_endpoint().address()<<std::endl; 
        boost::system::error_code ec; 
        socket.write_some(buffer("hello world1"), ec);

        if(ec){
            std::cout<<boost::system::system_error(ec).what()<<std::endl; 
            break; 
        }
    }
    return 0;
}

异步客户端

// 异步客户端
using boost::asio;
io_service service;
ip::tcp::endpoint ep( ip::address::from_string("127.0.0.1"), 2001);
ip::tcp::socket sock(service);
sock.async_connect(ep, connect_handler);
service.run();
void connect_handler(const boost::system::error_code & ec) {
    // 如果ec表示“成功”我们就可以知道连接成功了
}

异步服务端

// 异步服务端
using boost::asio;
typedef boost::shared_ptr socket_ptr;
io_service service;
ip::tcp::endpoint ep( ip::tcp::v4(), 2001)); // 监听端口2001
ip::tcp::acceptor acc(service, ep);
socket_ptr sock(new ip::tcp::socket(service));
start_accept(sock);
service.run();
void start_accept(socket_ptr sock) {
    acc.async_accept(*sock, boost::bind( handle_accept, sock, _1) );
}
void handle_accept(socket_ptr sock, const boost::system::error_code &err) {
    if (err) return;
    // 从这里开始, 你可以从socket读取或者写入
    socket_ptr sock(new ip::tcp::socket(service));
    start_accept(sock);
}

联系我们

微信号:shidaping023