zoukankan      html  css  js  c++  java
  • handy源码阅读(六):tcp类

    首先是tcpconn和tcpserver类:

    struct TcpConn : public std::enable_shared_from_this<TcpConn>, private noncopyable {
    enum State {
    Invalid = 1,
    Handshaking,
    Connected,
    Closed,
    Failed,
    };
    TcpConn();
    virtual ~TcpConn();
    template <class C = TcpConn>
    static TcpConnPtr createConnection(EventBase* base, const std::string& host, unsigned short port, int timeout = 0, const std::string& localip = "") {
    TcpConnPtr con(new C);
    con->connect(base, host, port, timeout, localip);
    return con;
    }
    template <class C = TcpConn>
    static TcpConnPtr createConnection(EventBase* base, int fd, Ip4Addr local, Ip4Addr peer) {
    TcpConnPtr con(new C);
    con->attach(base, fd, local, peer);
    return con;
    }
    bool isClient() {
    return destPort_ > 0;
    }
    template <class T>
    T& context() {
    return ctx_.context<T>();
    }
    EventBase* getBase() {
    return base_;
    }
    State getState() {
    return state_;
    }
    Buffer& getInput() {
    return input_;
    }
    Buffer& getOutput() {
    return output_;
    }
    Channel* getChannel() {
    return channel_;
    }
    bool writable() {
    return channel_ ? channel_->writeEnabled() : false;
    }
    void sendOutput() {
    send(output_);
    }
    void send(Buffer& msg);
    void send(const char* buf, size_t len);
    void send(const std::string& s) {
    send(s.data(), s.size());
    }
    void send(const char* s) {
    send(s, strlen(s));
    }

    void onRead(const TcpCallBack& cb) {
    assert(!readcb_);
    readcb_ = cb;
    } };
    struct TcpServer : private noncopyable {
      TcpServer(EventBase* bases);
    int bind(const std::string& host, unsigned short port, bool reusePort = false);
    static TcpServerPtr startServer(EventBases* bases, const std::string& host, unsigned short port, bool reusePort = false);
    ~TcpServer() {
    delete listen_channel_;
    }
    Ip4Addr getAddr() {
    return addr_;
    }
    EventBase* getBase() {
    return base_;
    }
    void onConnCreate(const std::function<TcpConnPtr()>& cb) {
    createcb_ = cb;
    }
    void onConnRead(const TcpCallBack& cb) {
    readcb_ = cb;
    assert(!msgcb_);
    }

    private:
    EventBase* base_;
    EventBases* bases_;
    Ip4Addr addr_;
    Channel* listen_channel_;
    TcpCallBack statecb_, readcb_;
    MsgCallBack msgcb_;
    std::function<TcpConnPtr()> createcb_;
    std::unique_ptr<CodecBase> codec_;
    void handleAccept(); };

     tcp类和udp类实现很相似,除了在处理连接监听方式不同外,都是用epoll_wait来等待内核通知处理指定的文件描述符的事件。

  • 相关阅读:
    CSS基础
    数据库优化之SQL Server
    压力测试与系统调优
    JBoss架构分析
    JBoss基本配置
    深入了解硬盘结构
    EJB2与EJB3架构对比
    JBoss高级配置
    病毒分类及病毒命名规则详解
    深入讲解防火墙的概念原理与实现
  • 原文地址:https://www.cnblogs.com/sssblog/p/11753856.html
Copyright © 2011-2022 走看看