結構
TcpClient
Connector
TcpConnection
Connector連接成功回調
創建TcpConnection,將TcpClient 設置的connectionCallback_, messageCallback_和writeCompleteCallback_傳遞到TcpConnection,同時設置關閉連接的回調removeConnection 執行connectEstablished
void TcpClient :: newConnection ( int sockfd)
{ loop_-> assertInLoopThread ( ) ; InetAddress peerAddr ( sockets:: getPeerAddr ( sockfd) ) ; char buf[ 32 ] ; snprintf ( buf, sizeof buf, ":%s#%d" , peerAddr. toIpPort ( ) . c_str ( ) , nextConnId_) ; ++ nextConnId_; string connName = name_ + buf; InetAddress localAddr ( sockets:: getLocalAddr ( sockfd) ) ; TcpConnectionPtr conn ( new TcpConnection ( loop_, connName, sockfd, localAddr, peerAddr) ) ; conn-> setConnectionCallback ( connectionCallback_) ; conn-> setMessageCallback ( messageCallback_) ; conn-> setWriteCompleteCallback ( writeCompleteCallback_) ; conn-> setCloseCallback ( std:: bind ( & TcpClient:: removeConnection, this , _1) ) ; { MutexLockGuard lock ( mutex_) ; connection_ = conn; } conn-> connectEstablished ( ) ;
}