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

posted @ 2019-10-28 17:41  c++11  阅读(346)  评论(0编辑  收藏  举报