C++:使用boost创建TCP服务

#include <iostream>
#include <boost/asio.hpp>

using boost::asio::ip::tcp;

int main() {
    try {
        boost::asio::io_context io_context;

        // 创建一个 TCP acceptor,监听本地的 12345 端口
        tcp::acceptor acceptor(io_context, tcp::endpoint(tcp::v4(), 12345));

        std::cout << "Server started. Listening on port 12345...\n";

        while (true) {
            // 等待客户端连接
            tcp::socket socket(io_context);
            acceptor.accept(socket);

            std::cout << "Client connected: " << socket.remote_endpoint() << std::endl;

            // 读取数据并实时打印
            boost::asio::streambuf receive_buffer;
            while (boost::asio::read(socket, receive_buffer, boost::asio::transfer_at_least(1))) {
                std::cout << "Received: " << &receive_buffer << std::endl;
                receive_buffer.consume(receive_buffer.size());

                std::string reply = "Hello, client!";
                // 回复客户端,会阻塞
                socket.send(boost::asio::buffer(reply));
                // 回复客户端,不阻塞
                boost::asio::write(socket, boost::asio::buffer(reply));
            }
        }
    } catch (std::exception &e) {
        std::cerr << "Exception: " << e.what() << std::endl;
    }

    return 0;
}

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值