• 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来等待内核通知处理指定的文件描述符的事件。

  • 相关阅读:
    Unity 关于特效和UI显示的优先级问题
    使用Frida神器轻松实现hook C/C++方法
    理解 Android Binder 机制(三):Java层
    理解 Android Binder 机制(二):C++层
    理解 Android Binder 机制(一):驱动篇
    Android Hook Instrumentation
    Cocos Creator 中根据uuid快速定位资源
    android 通用混淆配置
    vToRay + bbr 加速
    SpringBoot项目单元测试
  • 原文地址:https://www.cnblogs.com/sssblog/p/11753856.html
Copyright © 2020-2023  润新知