街角_祝福

导航

【ASIO】同步TCP客户端

#include <iostream>
#include <string>
#include <asio.hpp>

void test_tcp_client();
int main()
{
    try
    {
        test_tcp_client();
    }
    catch(std::exception& e)
    {
        std::cout << "执行异常:" << e.what() << std::endl;
    }
    return 0;
}
void test_tcp_client()
{
    asio::io_context ioc;
    asio::ip::tcp::resolver resolver(ioc);
    asio::ip::tcp::socket socket(ioc);
    asio::ip::tcp::endpoint ep(asio::ip::address::from_string("172.253.80.105"), 8080);
    socket.connect(ep);
    if(!socket.is_open())
    {
        std::cout << "连接服务器失败" << std::endl;
        return;
    }

    int buf_len = 0;
    char buf[64] = {0};
    for(int i = 0; i < 100; i++)
    {
        snprintf(buf, sizeof(buf) - 1, "我发送的数据:Hello%d", i + 1);
        asio::write(socket, asio::buffer(buf));
        std::cout << "发生数据:" << buf << std::endl;

        buf_len = socket.read_some(asio::buffer(buf));
        if(buf_len > 0)
        {
            buf[buf_len] = '\0';
            std::cout << "接收数据:" << buf << std::endl;
        }
        else if(buf_len == 0)
        {
            std::cout << "服务器已关闭" << std::endl;
            break;
        }
        else
        {
            std::cout << "接收数据异常" << std::endl;
            break;
        }
    }
}

posted on 2022-08-16 16:58  街角_祝福  阅读(137)  评论(0编辑  收藏  举报