【sylar】框架篇-Chapter14-TcpServer 模块

本文介绍了如何基于C++重写Sylar框架的TcpServer,包括配置结构、多地址绑定、协程调度及TemplatePattern设计模式的应用。特别关注高性能和并发处理的实现。

站在巨人的肩膀上

C++高性能分布式服务器框架

从零开始重写sylar C++高性能分布式服务器框架

概述

  • TCP 服务器的封装。

TcpServerConf

  • TcpServer 配置结构体。
  • 两个模板偏特化:
    • template<> class LexicalCast<std::string, TcpServerConf>
    • template<> class LexicalCast<TcpServerConf, std::string>

TcpServer

  • 继承自 std::enable_shared_from_this 和 sylar::Noncopyable。
  • TcpServer 类支持同时绑定多个地址进行监听,只需要在绑定时传入地址数组即可。有两个重载的 bind 方法。
  • TcpServer 还可以分别指定接收客户端和处理客户端的协程调度器。具体是 m_acceptWorker 和 m_ioWorker。

其他说明

  • TcpServer 类采用了模板模式(Template Pattern)的设计模式,它的 HandleClient 是交由继承类来实现的。使用 TcpServer 时,必须从 TcpServer 派生一个新类,并重新实现子类的 handleClient 操作。
  • 在模板模式(Template Pattern)中,一个抽象类公开定义了执行它的方法的方式/模板。它的子类可以按需要重写方法实现,但调用将以抽象类中定义的方式进行。这种类型的设计模式属于行为型模式。

待完善

  • 暂未调试支持 SSL。

部分相关代码

/**
 * @filename    tcp_server.h
 * @brief   Tcp 服务器的封装
 * @author  L-ge
 * @version 0.1
 * @modify  2022-07-13
 */
#ifndef __SYLAR_TCP_SERVER_H__
#define __SYLAR_TCP_SERVER_H__

#include <memory>
#include <functional>
#include "address.h"
#include "iomanager.h"
#include "socket.h"
#include "noncopyable.h"
#include "config.h"

namespace sylar
{

/**
 * @brief   TcpServer配置结构体
 */
struct TcpServerConf
{
    typedef std::shared_ptr<TcpServerConf> ptr;

    std::vector<std::string> address;
    int keepalive = 0;
    int timeout = 1000 * 2 * 60;
    int ssl = 0;
    std::string id;

    // 服务器类型:http、ws、rock
    std::string type = "http";
    std::string name;
    std::string cert_file;
    std::string key_file;
    std::string accept_worker;
    std::string io_worker;
    std::string process_worker;
    std::map<std::string, std::string> args;

    bool isValid() const
    {
        return !address.empty();
    }

    bool operator==(const TcpServerConf& oth) const
    {
        return address == oth.address
            && keepalive == oth.keepalive
            && timeout == oth.timeout
            && name == oth.name
            && ssl == oth.ssl
            &&am
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值