void TCPClient::DownloadFile(string fileName) { auto file = new fstream(); OpenFile(file, GetLocalFileName(fileName)); fpos_t currentProgress = file->tellp(); fpos_t fileSize = 0; auto done = false; cout << "Download started." << endl; while (!done) { try { SendMessage(this->_tcp_socket, CreateFileInfo(fileName, currentProgress)); fileSize = ReceiveFileSize(); ReceiveFile(file, currentProgress, fileSize); done = true; } catch (ConnectionInterrupted e) { currentProgress = e.GetProgress(); Reconnect(); } catch (ServerError) { file->close(); throw; } catch (runtime_error e) { cout << e.what() << endl; Reconnect(); } } file->close(); cout << "Done." << endl; }
bool MSqlQuery::exec(const QString &query) { if (!m_db) { // Database structure's been deleted return false; } // Database connection down. Try to restart it, give up if it's still // down if (!m_db->isOpen() && !Reconnect()) { LOG(VB_GENERAL, LOG_INFO, "MySQL server disconnected"); return false; } bool result = QSqlQuery::exec(query); // if the query failed with "MySQL server has gone away" // Close and reopen the database connection and retry the query if it // connects again if (!result && QSqlQuery::lastError().number() == 2006 && Reconnect()) result = QSqlQuery::exec(query); LOG(VB_DATABASE, LOG_INFO, QString("MSqlQuery::exec(%1) %2%3") .arg(m_db->MSqlDatabase::GetConnectionName()).arg(query) .arg(isSelect() ? QString(" <<<< Returns %1 row(s)") .arg(size()) : QString())); return result; }
bool MSqlQuery::prepare(const QString& query) { if (!m_db) { // Database structure's been deleted return false; } m_last_prepared_query = query; #ifdef DEBUG_QT4_PORT if (query.contains(m_testbindings)) { LOG(VB_GENERAL, LOG_DEBUG, QString("\n\nQuery contains bind value \"%1\" twice:\n\n\n") .arg(m_testbindings.cap(1)) + query); #if 0 exit(1); #endif } #endif // Database connection down. Try to restart it, give up if it's still // down if (!m_db) { // Database structure has been deleted... return false; } if (!m_db->isOpen() && !Reconnect()) { LOG(VB_GENERAL, LOG_INFO, "MySQL server disconnected"); return false; } bool ok = QSqlQuery::prepare(query); // if the prepare failed with "MySQL server has gone away" // Close and reopen the database connection and retry the query if it // connects again if (!ok && QSqlQuery::lastError().number() == 2006 && Reconnect()) ok = true; if (!ok && !(GetMythDB()->SuppressDBMessages())) { LOG(VB_GENERAL, LOG_ERR, QString("Error preparing query: %1").arg(query)); LOG(VB_GENERAL, LOG_ERR, MythDB::DBErrorMessage(QSqlQuery::lastError())); } return ok; }
uint32_t CommandsHandler::cmd_verbose(const tstring& cmd) { while (true) { if (GetAsyncKeyState(0x1b)) // [esc]退出循环 { break; } // 将命令通过管道发给服务端 if (!SendCMDToPipe(cmd)) { tprintf(TEXT("X [shell] send command \"%s\" error!\n"), cmd.c_str()); if (!Reconnect(true)) { tprintf(TEXT(" [shell] press any key to exit ...\n")); int ich = _getch(); exit(0); } } // 获取服务端的返回信息 uint32_t nRead; char* readBuff = new char[CPipeIO::MAX_PIPEMSG_LEN + 1]; if (!GetResponseFromPipe(readBuff, nRead)) { delete[] readBuff; tprintf(TEXT("X [shell] get response error!\n")); if (!Reconnect()) { tprintf(TEXT(" [shell] press any key to exit ...\n")); int ich = _getch(); exit(0); } else { return 0; } } if (nRead == 0) { delete[] readBuff; return 0; } // 显示返回信息 if (strcmp(readBuff,"<null>\n")!=0) tprintf(TEXT("%s"), readBuff); delete[] readBuff; Sleep(IDLE_TIME); } return 0; }
//update wave_detail_rpt set efile=%d where bool SPostgres::UpdateLobFromFile(SString sTable,SString sLobField,SString sWhere,SString sFile) { LOGBASEDEBUG("Into SPostgres::UpdateLobFromFile(%s,%s,%s,%s)", sTable.data(),sLobField.data(),sWhere.data(),sFile.data()); SString sql; Oid oid; SString param; PGresult *pRes = PQexec(m_pConn, "begin"); if(pRes == NULL) { if(TestConnect() == true)//连接可用 { LOGERROR("Error in SPostgres::UpdateLobFromFile, exec begin error, err=%s", PQerrorMessage(m_pConn)); return false; } //失败自动重连一次数据库 if(!Reconnect()) { LOGERROR("Error in SPostgres::UpdateLobFromFile, exec begin error, err=%s", PQerrorMessage(m_pConn)); return false; } pRes = PQexec(m_pConn, "begin"); if(pRes == NULL) { LOGERROR("Error in SPostgres::UpdateLobFromFile, exec begin error, err=%s", PQerrorMessage(m_pConn)); return false; } } PQclear(pRes); oid = lo_import(m_pConn, sFile.data()); if(oid == 0) { LOGERROR("Error in SPostgres::UpdateLobFromFile(%s,%s,%s,%s), err=%s", sTable.data(),sLobField.data(),sWhere.data(),sFile.data(),PQerrorMessage(m_pConn)); pRes = PQexec(m_pConn, "end"); if(pRes != NULL) PQclear(pRes); return false; } sql.sprintf("update %s set %s=%d where %s",sTable.data(),sLobField.data(),oid,sWhere.data()); pRes = PQexec(m_pConn, sql.data()); LOGBASEDEBUG("%s",sql.data()); if(pRes == NULL || PQresultStatus(pRes) != PGRES_COMMAND_OK ) { LOGERROR("Error in SPostgres::UpdateLobFromFile(%s,%s,%s,%s), sql=%s, err=%s", sTable.data(),sLobField.data(),sWhere.data(),sFile.data(),sql.data(),PQerrorMessage(m_pConn)); lo_unlink(m_pConn,oid); if(pRes != NULL) PQclear(pRes); pRes = PQexec(m_pConn, "end"); if(pRes != NULL) PQclear(pRes); return false; } PQclear(pRes);//add by skt at 2007-9-13不清除将导致内存缓慢增长 pRes = PQexec(m_pConn, "end"); if(pRes != NULL) PQclear(pRes); return pRes != NULL; }
int CExchangeServer::GetUnreadEmailsCount() { int nCount = -1; #ifndef NO_EXCHANGE_TEST HRESULT hRes = CheckForNewMails(nCount); if (hRes!=S_OK) { Reconnect(); if (IsConnected()) { hRes = CheckForNewMails(nCount); } else { nCount = -1; } } #else nCount = 3; #endif return nCount; }
MYSQL_RES* CDatabase::QUse( const char *Format, ...) { bool Qfail = true; //char query[1024]; char query[80000]; va_list ap; va_start( ap, Format ); vsprintf( query, Format, ap ); va_end ( ap ); result = NULL; Log( MSG_QUERY,"IN Quse:: %s",query ); pthread_mutex_lock( &SQLMutex ); while(Qfail) { if(mysql_query( Mysql, query )!=0) { Log( MSG_FATALERROR, "Could not execute query: %s", mysql_error( Mysql ) ); if(Reconnect( )==-1) { Log( MSG_FATALERROR, "Could not execute query: %s", mysql_error( Mysql ) ); pthread_mutex_unlock( &SQLMutex ); //return false; return NULL; } else Qfail = false; } else Qfail = false; } result = mysql_use_result( Mysql ); //Log( MSG_QUERY,"OUT Quse"); return result; }
// execute query bool CDatabase::QExecute( const char *Format,... ) { bool Qfail = true; //char query[1024]; //char query[1300]; //LMA: sometimes we need more... char query[80000]; va_list ap; va_start( ap, Format ); vsprintf( query, Format, ap ); va_end ( ap ); Log( MSG_QUERY,"IN QExec:: %s",query ); int no_err=0; no_err=pthread_mutex_lock( &SQLMutex ); while(Qfail) { if(mysql_query( Mysql, query )!=0) { Log( MSG_FATALERROR, "Could not execute query: %s", mysql_error( Mysql ) ); if(Reconnect( )==-1) { Log( MSG_FATALERROR, "Could not execute query: %s", mysql_error( Mysql ) ); pthread_mutex_unlock( &SQLMutex ); return false; } else Qfail = false; } else Qfail = false; } pthread_mutex_unlock( &SQLMutex ); //Log( MSG_QUERY,"OUT:: QExec"); return true; }
bool TcpClient::Connect() { bool success = Connect_(); if (!success && auto_reconnect_) Reconnect(); return success; }
/*--- Timeout has expired, restart file ---*/ void Downloader::Reconnect() { qDebug() << "Downloader::Reconnect"; // Suppress the FTP handler emit Log("Timeout downloading " + currentFtpFile, false); disconnect(timeoutTimer, SIGNAL(timeout()), this, SLOT(Reconnect())); disconnect(ftp, SIGNAL(finished(QNetworkReply*)), this, SLOT(FileFinished(QNetworkReply*))); ftp->deleteLater(); // Restart it ftp = new QNetworkAccessManager(); connect(timeoutTimer, SIGNAL(timeout()), this, SLOT(Reconnect())); connect(ftp, SIGNAL(finished(QNetworkReply*)), this, SLOT(FileFinished(QNetworkReply*))); emit DownloadFile(currentFtpDir, currentFtpFile); }
QList<DeviceFinder::Device> PulseDeviceFinder::ListDevices() { if (!context_ || pa_context_get_state(context_) != PA_CONTEXT_READY) { return QList<Device>(); } retry: ListDevicesState state; pa_context_get_sink_info_list( context_, &PulseDeviceFinder::GetSinkInfoCallback, &state); forever { if (state.finished) { return state.devices; } switch (pa_context_get_state(context_)) { case PA_CONTEXT_READY: break; case PA_CONTEXT_FAILED: case PA_CONTEXT_TERMINATED: // Maybe pulseaudio died. Try reconnecting. if (Reconnect()) { goto retry; } return state.devices; default: return state.devices; } pa_mainloop_iterate(mainloop_, true, nullptr); } }
//LMA: Special Update case, returns nb affected rows. int CDatabase::QExecuteUpdate( const char *Format,... ) { bool Qfail = true; //char query[1024]; char query[80000]; va_list ap; va_start( ap, Format ); vsprintf( query, Format, ap ); va_end ( ap ); Log( MSG_QUERY, "IN:: ExecU: %s",query ); pthread_mutex_lock( &SQLMutex ); while(Qfail) { if(mysql_query( Mysql, query )!=0) { Log( MSG_FATALERROR, "Could not execute query: %s", mysql_error( Mysql ) ); if(Reconnect( )==-1) { Log( MSG_FATALERROR, "Could not execute query: %s", mysql_error( Mysql ) ); pthread_mutex_unlock( &SQLMutex ); return -1; } else Qfail = false; } else Qfail = false; } pthread_mutex_unlock( &SQLMutex ); //Log( MSG_QUERY, "OUT ExecU"); return mysql_affected_rows(Mysql); }
BOOL CWaveSession::Login(wstring szUsername, wstring szPassword) { ASSERT(!szUsername.empty() && !szPassword.empty()); if (m_nState != WSS_OFFLINE) { LOG("Not offline"); return FALSE; } if (m_lpRequest != NULL) { LOG("Requesting login while a request is running"); return FALSE; } m_nState = WSS_CONNECTING; SignalProgress(WCS_BEGIN_LOGON); m_szUsername = szUsername; m_szPassword = szPassword; return Reconnect(); }
void CGeneralAgentTcpSocketConnector::OnDelete() { if (m_b_connected) { Reconnect(); } }
void ZKAgent::OnCreated(const std::string& path, int rc) { DEBUG_LOG("Create %s on zk with rc:%d", path.c_str(), rc); if (rc == ZOK || rc == ZNODEEXISTS) { switch (m_state) { case ZK_STATE_CREATE_NODE: { m_state = ZK_STATE_CONNECTED; break; } default: { ERROR_LOG("Invalid state:%d", m_state); break; } } } else { ERROR_LOG("Failed to create path:%s at state:%d for reason:%s", path.c_str(), m_state, zerror(rc)); //OnSessionExpired(); memset(&m_zk_clientid, 0, sizeof(m_zk_clientid)); Reconnect(); } }
void TcpClient::OnConnectionClosed(TcpConnection* conn) { //delete conn_; conn_ = nullptr; if (auto_reconnect_) { Reconnect(); } }
void ZKAgent::OnSessionExpired() { DEBUG_LOG("ZK session expired."); memset(&m_zk_clientid, 0, sizeof(m_zk_clientid)); ArdbServerConfig& cfg = m_server->m_cfg; std::string zkidfile = cfg.home + "/.zkcid"; unlink(zkidfile.c_str()); Reconnect(); }
bool PulseDeviceFinder::Initialise() { mainloop_ = pa_mainloop_new(); if (!mainloop_) { qLog(Warning) << "Failed to create pulseaudio mainloop"; return false; } return Reconnect(); }
int SPostgres::Retrieve(SString sql,SRecordset &rs) { LOGBASEDEBUG("into SPostgres::Retrieve(%s)",sql.data()); sql = sql.replace("\\","\\\\");//postgres数据库SQL中\为转义符 if(m_pConn == NULL) { LOGWARN("m_pConn is NULL is SPostgres::Retrieve, Connect it at first!"); Connect(); if(m_pConn == NULL) { LOGWARN("m_pConn is NULL is SPostgres::Retrieve, Connect error!"); return -1; } } PGresult *pRes = PQexec(m_pConn,sql.data()); if(PQresultStatus(pRes) != PGRES_TUPLES_OK) { if(pRes != NULL) PQclear(pRes); if(TestConnect() == true)//连接可用 return -1; //连接不可用自动重连一次数据库 if(!Reconnect()) return -2;//连接失败 pRes = PQexec(m_pConn,sql.data()); if(PQresultStatus(pRes) != PGRES_TUPLES_OK) { if(pRes != NULL) PQclear(pRes); return -1; } } int cols = PQnfields(pRes); int rows = PQntuples(pRes); int i,j; SRecord *pRecord; //写入记录集 rs.clear(); rs.SetSize(rows,cols); for(i=0;i<cols;i++) { rs.SetColumnName(i,PQfname(pRes,i)); } for(i=0;i<rows;i++) { pRecord = rs.GetRecord(i); for(j=0;j<cols;j++) { pRecord->SetValue(j,PQgetvalue(pRes,i,j)); } } PQclear(pRes); return rows; }
uint32_t CommandsHandler::cmd_system(const tstring& cmd) { // 将命令通过管道发给服务端 if(!SendCMDToPipe(cmd)) { tprintf(TEXT("X [shell] send command \"%s\" error!\n"),cmd.c_str()); if (!Reconnect(true)) { tprintf(TEXT(" [shell] press any key to exit ...\n")); int ich = _getch(); exit(0); } } // 获取服务端的返回信息 uint32_t nRead; char* readBuff = new char[CPipeIO::MAX_PIPEMSG_LEN + 1]; if(!GetResponseFromPipe(readBuff, nRead)) { delete[] readBuff; tprintf(TEXT("X [shell] get response error!\n")); if (!Reconnect()) { tprintf(TEXT(" [shell] press any key to exit ...\n")); int ich = _getch(); exit(0); } else { return 0; } } if (nRead == 0) { delete[] readBuff; return 0; } // 显示返回信息 tprintf(TEXT("%s\n"), readBuff); delete[] readBuff; return 0; }
void _XawImReconnect(Widget inwidg) { XawVendorShellExtPart *ve; VendorShellWidget vw; if ((vw = SearchVendorShell(inwidg)) == NULL) return; if ((ve = GetExtPart(vw)) != NULL) { Reconnect(ve); } }
bool SPostgres::ReadLobToFile(SString sTable,SString sLobField,SString sWhere,SString sFile) { LOGBASEDEBUG("Into SPostgres::ReadLobToFile(%s,%s,%s,%s)", sTable.data(),sLobField.data(),sWhere.data(),sFile.data()); SString sql; sql.sprintf("select %s from %s where %s",sLobField.data(),sTable.data(),sWhere.data()); Oid oid = SelectIntoI(sql); if(oid == 0) { LOGERROR("Into SPostgres::ReadLobToFile(%s,%s,%s,%s) get oid error, oid=0", sTable.data(),sLobField.data(),sWhere.data(),sFile.data()); return false; } PGresult *pRes = PQexec(m_pConn, "begin"); if(pRes == NULL) { if(TestConnect() == true)//连接可用 { LOGERROR("Error in SPostgres::ReadLobToFile, exec begin error, err=%s", PQerrorMessage(m_pConn)); return false; } //失败自动重连一次数据库 if(!Reconnect()) { LOGERROR("Error in SPostgres::ReadLobToFile, exec begin error, err=%s", PQerrorMessage(m_pConn)); return false; } pRes = PQexec(m_pConn, "begin"); if(pRes == NULL) { LOGERROR("Error in SPostgres::ReadLobToFile, exec begin error, err=%s", PQerrorMessage(m_pConn)); return false; } } PQclear(pRes); pRes = NULL; if(lo_export(m_pConn,oid,sFile.data()) == 0) { LOGERROR("Error in SPostgres::ReadLobToFile(%s,%s,%s,%s), lo_export error, err:%s", sTable.data(),sLobField.data(),sWhere.data(),sFile.data(),PQerrorMessage(m_pConn)); pRes = PQexec(m_pConn, "end"); if(pRes != NULL) PQclear(pRes); return false; } if(pRes != NULL) PQclear(pRes); pRes = PQexec(m_pConn, "end"); if(pRes != NULL) PQclear(pRes); return pRes != NULL; }
/*--- Received when a command has failed ---*/ void Downloader::FileError(QNetworkReply::NetworkError code) { qDebug() << "Downloader::FileError on " + currentFtpDir + currentFtpFile; switch (code) { case QNetworkReply::NoError: break; case QNetworkReply::ConnectionRefusedError: case QNetworkReply::RemoteHostClosedError: case QNetworkReply::HostNotFoundError: case QNetworkReply::TimeoutError: qDebug() << "Downloader::FileError : network error " + QString::number(code); Log("Networking error (" + QString::number(code) + ")", true); break; case QNetworkReply::AuthenticationRequiredError: qDebug() << "Downloader::FileError : authentication error " + QString::number(code); #if USE_PASSWORD Log("Invalid password", true); #else Log("Password is required", true); #endif Log("This IP address will be temporary banned after too many invalid passwords", true); timeoutTimer->stop(); speedUpdateTimer->stop(); #if USE_PASSWORD disconnect(timeout, SIGNAL(timeout()), this, SLOT(Reconnect())); disconnect(ftp, SIGNAL(finished(QNetworkReply*)), this, SLOT(FileFinished(QNetworkReply*))); ftp->deleteLater(); timeout->deleteLater(); speedUpdateTimer->deleteLater(); emit Connect(); #endif break; case QNetworkReply::ProxyAuthenticationRequiredError: case QNetworkReply::ProxyConnectionRefusedError: case QNetworkReply::ProxyConnectionClosedError: case QNetworkReply::ProxyNotFoundError: case QNetworkReply::ProxyTimeoutError: case QNetworkReply::UnknownProxyError: qDebug() << "Downloader::FileError : proxy error " + QString::number(code); Log("Proxy error (" + QString::number(code) + ")", true); break; default: qDebug() << "Downloader::FileError : server error " + QString::number(code); Log("Server error (" + QString::number(code) + ")", true); break; } }
int CExchangeServer::Check(int bNoEmailsNotify) { int count = -1; if (IsConnected()) { count = GetUnreadEmailsCount(); if (count == -1) { Reconnect(); if (IsConnected()) count = GetUnreadEmailsCount(); else return -1; } } else { Reconnect(); if (IsConnected()) count = GetUnreadEmailsCount(); else return -1; if (count==-1) return -1; } if (((count > 0) || ((bNoEmailsNotify) && (count >= 0))) && (count != -1)) { TCHAR buffer[1024]; if (count != 1) mir_sntprintf(buffer, SIZEOF(buffer), TranslateT("You have %d unread emails..."), count); else mir_sntprintf(buffer, SIZEOF(buffer), TranslateT("You have one unread email...")); ShowMessage(buffer, count); } if (count==-1) _popupUtil("Cannot connect to Exchange server..."); return count; }
int ClientConn::SendPacket(PktBase* pPkt) { if (conn_handle_ == NETLIB_INVALID_HANDLE) { return 0; } if (is_socket_closed(conn_handle_)) { int ret = Reconnect(); if (ret) { return 0; } } return block_send_all(conn_handle_, pPkt->GetBuffer(), pPkt->GetLength()); }
virtual void OnAction(int id) override { switch (id) { case CLEAR: Clear(); break; case RECONNECT: Reconnect(); break; case PAUSE: TogglePause(); break; } }
/*--- Launch thread ---*/ void Downloader::Connect() { qDebug() << "Downloader::Connect"; // Files init QFile::remove(FTP_OLD_RELEASE_NOTES_FILE); QFile::copy(FTP_RELEASE_NOTES_FILE, FTP_OLD_RELEASE_NOTES_FILE); QFile::remove(FTP_RELEASE_NOTES_FILE); QFile::remove(FTP_MANIFEST_FILE); // URL setup baseUrl = new QUrl(); baseUrl->setScheme("ftp"); baseUrl->setPort(21); baseUrl->setHost(FTP_SERVER); baseUrl->setUserName(FTP_USER); // FTP setup currentSpeed = 0.0; currentFtpFile = ""; ftp = new QNetworkAccessManager(); connect(ftp, SIGNAL(finished(QNetworkReply*)), this, SLOT(FileFinished(QNetworkReply*))); // Timers chrono = new QTime(); timeoutTimer = new QTimer(this); speedUpdateTimer = new QTimer(this); downloadUpdateTimer = new QTimer(this); connect(timeoutTimer, SIGNAL(timeout()), this, SLOT(Reconnect())); connect(speedUpdateTimer, SIGNAL(timeout()), this, SLOT(UpdateSpeedInfo())); connect(downloadUpdateTimer, SIGNAL(timeout()), this, SLOT(UpdateDownloadInfo())); // Chrono chronoSize = 0; chrono->start(); speedUpdateTimer->setSingleShot(true); speedUpdateTimer->start(FTP_SPEED_UPDATE_TIME); downloadUpdateTimer->setSingleShot(true); downloadUpdateTimer->start(FTP_DOWNLOAD_UPDATE_TIME); // Launch #if USE_PASSWORD emit AskForPassword(); #else Login(""); #endif }
bool ITGIO::Write( const uint32_t iData ) { int iResult; while( 1 ) { iResult = usb_control_msg(m_pHandle, USB_ENDPOINT_OUT | USB_TYPE_CLASS | USB_RECIP_INTERFACE, HID_SET_REPORT, HID_IFACE_OUT, 0, (char *)&iData, 4, 1000 ); if( iResult == 4 ) // all data read break; Reconnect(); } return true; }
bool MsgConnection::SendRequest(MsgPacket* request) { if(IsAborting()) { return false; } // restore connection if needed if(GetConnectionLost() && !Reconnect()) { return false; } if(!request->write(m_socket, m_timeout)) { SetConnectionLost(); return false; } return true; }
int ZKAgent::Init(ArdbServer* serv) { m_server = serv; ArdbServerConfig& cfg = serv->m_cfg; if (cfg.zookeeper_servers.empty()) { WARN_LOG("No zookeeper servers specified, zookeeper agent would not start."); return 0; } ZooLogLevel z_log_loevel; if (DEBUG_ENABLED()) { z_log_loevel = ZOO_LOG_LEVEL_DEBUG; } else if (INFO_ENABLED()) { z_log_loevel = ZOO_LOG_LEVEL_INFO; } else if (WARN_ENABLED()) { z_log_loevel = ZOO_LOG_LEVEL_WARN; } else if (ERROR_ENABLED()) { z_log_loevel = ZOO_LOG_LEVEL_ERROR; } else { z_log_loevel = ZOO_LOG_LEVEL_DEBUG; } zoo_set_debug_level(z_log_loevel); zoo_set_log_stream(ArdbLogger::GetLogStream()); std::string zkidfile = cfg.home + "/.zkcid"; FILE* idfile = fopen(zkidfile.c_str(), "r"); if (idfile != NULL) { if (fread(&m_zk_clientid, sizeof(m_zk_clientid), 1, idfile) != 1) { memset(&m_zk_clientid, 0, sizeof(m_zk_clientid)); } fclose(idfile); } Reconnect(); return 0; }