1
2 3 4 5 6 |
// 连接关闭,回调TcpConnection::handleClose channel_->setCloseCallback( boost::bind(&TcpConnection::handleClose, this)); // 发生错误,回调TcpConnection::handleError channel_->setErrorCallback( boost::bind(&TcpConnection::handleError, this)); |
1
2 3 4 5 6 |
void TcpServer::newConnection(
int sockfd,
const InetAddress &peerAddr)
{ ..... conn->setCloseCallback( boost::bind(&TcpServer::removeConnection, this, _1)); } |
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
void TcpConnection::handleRead(Timestamp receiveTime) { ssize_t n = ::read(channel_->fd(), buf, sizeof buf); if (n > 0) { messageCallback_(shared_from_this(), buf, n); } else if (n == 0) { handleClose(); } else { errno = savedErrno; LOG_SYSERR << "TcpConnection::handleRead"; handleError(); } } |
1
2 3 4 5 6 7 8 9 10 |
void TcpConnection::handleClose()
{ setState(kDisconnected); channel_->disableAll(); TcpConnectionPtr guardThis(shared_from_this());
connectionCallback_(guardThis);
// must be the last line closeCallback_(guardThis); // 调用TcpServer::removeConnection } |
1
2 |
class TcpConnection : boost::noncopyable,
public boost::enable_shared_from_this<TcpConnection> |
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
#include<boost/enable_shared_from_this.hpp>
#include<boost/shared_ptr.hpp> #include<cassert> class Y: public boost::enable_shared_from_this<Y> { public: boost::shared_ptr<Y> f() { return shared_from_this(); } Y *f2() { return this; } }; int main( void) { boost::shared_ptr<Y> p( new Y); boost::shared_ptr<Y> q = p->f(); Y *r = p->f2(); assert(p == q); assert(p.get() == r); std::cout << p.use_count() << std::endl; //2 boost::shared_ptr<Y> s(r); std::cout << s.use_count() << std::endl; //1 assert(p == s); //断言失败 return 0; } |
1
2 3 4 5 6 7 8 |
void TcpServer::removeConnection(
const TcpConnectionPtr &conn)
{ size_t n = connections_.erase(conn->name()); loop_->queueInLoop( boost::bind(&TcpConnection::connectDestroyed, conn)); } |
1
2 3 4 5 6 7 8 9 10 11 12 |
void TcpConnection::connectDestroyed()
{ loop_->assertInLoopThread(); if (state_ == kConnected) { setState(kDisconnected); channel_->disableAll(); connectionCallback_(shared_from_this()); } channel_->remove(); //poll 不再关注此通道 } |