使用C++编写TCP服务端程序

要使用Boost.Asio库来开发一个TCP服务端程序,你需要遵循以下步骤。下面的示例代码将演示如何创建一个简单的异步TCP服务器,它能够接收客户端连接,并异步处理请求和响应。

首先,确保你已经安装了Boost库,并在你的项目中包含了asio库。

以下是基本的代码框架:

cpp 复制代码
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/system/error_code.hpp>
#include <iostream>
#include <memory>

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

class Server {
public:
    Server(boost::asio::io_context& io_context, short port)
        : acceptor_(io_context, tcp::endpoint(tcp::v4(), port))
    {
        // 启动监听
        start_accept();
    }

private:
    void start_accept() {
        // 创建新的socket
        std::shared_ptr<tcp::socket> new_socket = std::make_shared<tcp::socket>(acceptor_.get_executor().context());

        // 异步接受连接
        acceptor_.async_accept(*new_socket,
            [this, new_socket](boost::system::error_code ec) {
                if (!ec) {
                    std::cout << "New connection accepted." << std::endl;
                    // 异步读取请求数据
                    boost::asio::async_read(*new_socket, boost::asio::buffer(buffer_),
                        [this, new_socket](boost::system::error_code ec, std::size_t length) {
                            if (!ec) {
                                // 处理请求(这里只是简单地将接收到的数据原样返回)
                                boost::asio::async_write(*new_socket, boost::asio::buffer(buffer_, length),
                                    [new_socket](boost::system::error_code ec, std::size_t /*length*/) {
                                        if (ec) {
                                            std::cerr << "Error: " << ec.message() << std::endl;
                                        } else {
                                            std::cout << "Response sent successfully." << std::endl;
                                        }
                                    });
                            } else {
                                std::cerr << "Read failed: " << ec.message() << std::endl;
                            }
                        });

                    // 继续监听下一个连接
                    start_accept();
                } else {
                    std::cerr << "Accept failed: " << ec.message() << std::endl;
                }
            });
    }

    tcp::acceptor acceptor_;
    char buffer_[1024];
};

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

        Server s(io_context, 12345);

        io_context.run();
    }
    catch (std::exception& e) {
        std::cerr << e.what() << std::endl;
    }

    return 0;
}

在这个例子中:

  • 我们定义了一个Server类,它包含一个acceptor用于接受新连接。
  • start_accept函数用于启动异步接受过程,当有新的连接到达时,它会创建一个新的socket并绑定到一个lambda函数中,该函数处理读取请求、处理请求以及写入响应。
  • 请求数据被读取到buffer_中,然后原样返回给客户端。
  • 使用io_context.run()启动事件循环,处理所有的I/O操作。
相关推荐
自动驾驶小卡43 分钟前
boost::circular_buffer的使用方法简介
c++·boost·circular_buffer
编码浪子2 小时前
趣味学RUST基础篇(异步)
服务器·rust·负载均衡
爱睡觉的圈圈2 小时前
分布式IP代理集群架构与智能调度系统
分布式·tcp/ip·架构
睡不醒的kun3 小时前
leetcode算法刷题的第三十二天
数据结构·c++·算法·leetcode·职场和发展·贪心算法·动态规划
九河云3 小时前
华为云 GaussDB:金融级高可用数据库,为核心业务保驾护航
网络·数据库·科技·金融·华为云·gaussdb
独行soc3 小时前
2025年渗透测试面试题总结-66(题目+回答)
java·网络·python·安全·web安全·adb·渗透测试
码农101号3 小时前
运维安全05 - iptables规则保存与恢复
运维·网络·安全
Empty_7773 小时前
SELinux安全上下文
linux·服务器·安全
乔宕一5 小时前
stm32 链接脚本没有 .gcc_except_table 段也能支持 C++ 异常
c++·stm32·嵌入式硬件
SuperCandyXu5 小时前
P3205 [HNOI2010] 合唱队-普及+/提高
c++·算法·洛谷