结构
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 ( ) ;
}