void TCPClient::AfterRecv(uv_stream_t* handle, ssize_t nread, const uv_buf_t* buf) { TcpClientCtx* theclass = (TcpClientCtx*)handle->data; assert(theclass); TCPClient* parent = (TCPClient*)theclass->parent_server; if (nread < 0) { if (parent->reconnectcb_) { parent->reconnectcb_(NET_EVENT_TYPE_DISCONNECT, parent->reconnect_userdata_); } if (!parent->StartReconnect()) { fprintf(stdout, "Start Reconnect Failure.\n"); return; } if (nread == UV_EOF) { fprintf(stdout, "Server close(EOF), Client %p\n", handle); LOG(INFO) << ("Server close(EOF)"); } else if (nread == UV_ECONNRESET) { fprintf(stdout, "Server close(conn reset),Client %p\n", handle); LOG(INFO) << ("Server close(conn reset)"); } else { fprintf(stdout, "Server close,Client %p:%s\n", handle, GetUVError(nread).c_str()); LOG(INFO) << "Server close" << GetUVError(nread); } uv_close((uv_handle_t*)handle, AfterClientClose);//close before reconnect return; } parent->send_inl(NULL); if (nread > 0) { theclass->packet_->recvdata((const unsigned char*)buf->base, nread); } }
void TCPClient::AfterConnect(uv_connect_t* handle, int status) { TcpClientCtx* theclass = (TcpClientCtx*)handle->handle->data; TCPClient* parent = (TCPClient*)theclass->parent_server; if (status) { parent->connectstatus_ = CONNECT_ERROR; parent->errmsg_ = GetUVError(status); LOG(ERROR)<<"client(" << parent << ") connect error:" << parent->errmsg_; fprintf(stdout, "connect error:%s\n", parent->errmsg_.c_str()); if (parent->isreconnecting_) {//reconnect failure, restart timer to trigger reconnect. uv_timer_stop(&parent->reconnect_timer_); parent->repeat_time_ *= 2; uv_timer_start(&parent->reconnect_timer_, TCPClient::ReconnectTimer, parent->repeat_time_, parent->repeat_time_); } return; } int iret = uv_read_start(handle->handle, AllocBufferForRecv, AfterRecv); if (iret) { parent->errmsg_ = GetUVError(status); LOG(ERROR)<<"client(" << parent << ") uv_read_start error:" << parent->errmsg_; fprintf(stdout, "uv_read_start error:%s\n", parent->errmsg_.c_str()); parent->connectstatus_ = CONNECT_ERROR; } else { parent->connectstatus_ = CONNECT_FINISH; LOG(INFO) << "client(" << parent << ")run"; } if (parent->isreconnecting_) { fprintf(stdout, "reconnect succeed\n"); parent->StopReconnect();//reconnect succeed. if (parent->reconnectcb_) { parent->reconnectcb_(NET_EVENT_TYPE_RECONNECT, parent->reconnect_userdata_); } } }