void ClientCore::login(QString ipAddr, QString login, QString password) { if(connectToServer(ipAddr, SERVER_PORT)){ QString blockPrep; blockPrep.append(login); blockPrep.append(" "); blockPrep.append(hashPW(password)); QByteArray datablock; QDataStream in(&datablock, QIODevice::WriteOnly); in << blockPrep; this->sendBlock(ServerClient::loginComm,&datablock); } else { qDebug() << "cant connect"; } }
void loop() { if (client.connected()) { if (client.available()) { // read incoming bytes: char inChar = client.read(); // add incoming byte to end of line: currentLine += inChar; // if you get a newline, clear the line: if (inChar == '\n') { currentLine = ""; } // if the current line ends with <text>, it will // be followed by the tweet: if ( currentLine.endsWith("<text>")) { // tweet is beginning. Clear the tweet string: readingTweet = true; tweet = ""; } // if you're currently reading the bytes of a tweet, // add them to the tweet String: if (readingTweet) { if (inChar != '<') { tweet += inChar; } else { // if you got a "<" character, // you've reached the end of the tweet: readingTweet = false; Serial.println(tweet); // close the connection to the server: client.stop(); } } } } else if (millis() - lastAttemptTime > requestInterval) { // if you're not connected, and two minutes have passed since // your last connection, then attempt to connect again: connectToServer(); } }
void QXmppClient::connectToServer(const QString& host, const QString& bareJid, const QString& passwd, int port, const QXmppPresence& initialPresence) { QString user, domain; QStringList list = bareJid.split("@"); if(list.size() == 2) { user = list.at(0); domain = list.at(1); connectToServer(host, user, passwd, domain, port, initialPresence); } else { emit logMessage(QXmppLogger::WarningMessage, "Invalid bareJid"); } }
void QxmppPeer::connectHost( const std::string & jid, const std::string & password, const std::string & host, int port, bool tls ) { QXmppConfiguration conf; conf.setJid( jid.c_str() ); conf.setPassword( password.c_str() ); if ( host.size() > 0 ) conf.setHost( host.c_str() ); if ( port > 0 ) conf.setPort( port ); conf.setAutoReconnectionEnabled( true ); //conf.setUseNonSASLAuthentication( true ); if ( tls ) conf.setStreamSecurityMode( QXmppConfiguration::TLSEnabled ); else conf.setStreamSecurityMode( QXmppConfiguration::TLSDisabled ); connectToServer( conf ); }
void LTWindow::error(QNetworkReply::NetworkError er) { if (!playing) { ui->actionRecord->setEnabled(false); if (QMessageBox::critical(this, tr("Connection error!"), tr("There was an error with connection to LT server\n Error code: ") + QString("%1").arg(er), QMessageBox::Retry, QMessageBox::Close) == QMessageBox::Retry) { //try to connect again streamReader->disconnectFromLTServer(); connectToServer(); } // else // { // ui->messageBoardWidget->showStartupBoard(); // showSessionBoard(true); // } } }
/// public slots void CServerManager::TakeServerConnect(const Message::CMessageConnectToServerPtr pMessage) { if(!m_connectToServer) { connectToServer(pMessage->m_serverIP, pMessage->m_serverPort); sendToServer(pMessage); qDebug("Network - start wait confirm timer"); m_timerConfirm.start(); } else { Message::CMessageInformationPtr ptr(new Message::CMessageInformation); ptr->m_typeInformation = Message::CMessageInformation::eConnectionToServer; ptr->m_strInformation = "Error, You again trying connect to server"; emit SendInInformation(ptr); } }
int openConnection() { int s = connectToServer(localPort, remoteName, remotePort); int x = 1; if (setsockopt(s, SOL_TCP, TCP_NODELAY, &x, sizeof(int)) < 0) { perror("setsockopt(TCP_NODELAY)"); exit(1); } if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &x, sizeof(int)) < 0) { perror("setsockopt(SO_REUSEADDR)"); exit(1); } x = sizeof(GoBackNMessageStruct); if (setsockopt(s, SOL_SOCKET, SO_SNDBUF, &x, sizeof(int)) < 0) { perror("setsockopt(SO_SNDBUF)"); exit(1); } return s; }
void EtherIPC::waitConnect() { if ( fStarting == 1 ) { return init(); } if ( fStarting != 1 && fStarting != 2 ) { return connectionTimeout(); } if ( ++fConnectAttempts < 10 ) { if ( fSocket.state() == QLocalSocket::ConnectingState ) { fSocket.abort(); } connectToServer(); } else { connectionTimeout(); } }
void MainWindow::on_actionConnect_triggered() { ConnectDialog dialog(this); QByteArray temp; if(dialog.exec()){ temp = dialog.ui->lineEdit->text().toAscii(); strcpy(info->hostname, temp.data()); mySocket->port = dialog.ui->lineEdit_2->text().toInt(); if((sd = socket(AF_INET, SOCK_STREAM, 0)) == -1){ printf("error creating socket"); } else { mySocket->socket = sd; } if(connectToServer(mySocket, info)){ connected = true; } } }
/* * get_db_infos() * * Scans pg_database system catalog and populates all user * databases. */ static void get_db_infos(ClusterInfo *cluster) { PGconn *conn = connectToServer(cluster, "template1"); PGresult *res; int ntups; int tupnum; DbInfo *dbinfos; int i_datname, i_oid, i_spclocation; res = executeQueryOrDie(conn, "SELECT d.oid, d.datname, t.spclocation " "FROM pg_catalog.pg_database d " " LEFT OUTER JOIN pg_catalog.pg_tablespace t " " ON d.dattablespace = t.oid " "WHERE d.datallowconn = true " /* we don't preserve pg_database.oid so we sort by name */ "ORDER BY 2"); i_oid = PQfnumber(res, "oid"); i_datname = PQfnumber(res, "datname"); i_spclocation = PQfnumber(res, "spclocation"); ntups = PQntuples(res); dbinfos = (DbInfo *) pg_malloc(sizeof(DbInfo) * ntups); for (tupnum = 0; tupnum < ntups; tupnum++) { dbinfos[tupnum].db_oid = atooid(PQgetvalue(res, tupnum, i_oid)); snprintf(dbinfos[tupnum].db_name, sizeof(dbinfos[tupnum].db_name), "%s", PQgetvalue(res, tupnum, i_datname)); snprintf(dbinfos[tupnum].db_tblspace, sizeof(dbinfos[tupnum].db_tblspace), "%s", PQgetvalue(res, tupnum, i_spclocation)); } PQclear(res); PQfinish(conn); cluster->dbarr.dbs = dbinfos; cluster->dbarr.ndbs = ntups; }
/* -- FUNCTION: processConnection -- -- DATE: September 25, 2011 -- -- REVISIONS: (Date and Description) -- -- DESIGNER: Luke Queenan -- -- PROGRAMMER: Luke Queenan -- -- INTERFACE: void processConnection(int socket, char *ip, int port); -- -- RETURNS: void -- -- NOTES: -- This function is called after a client has connected to the server. The -- function will determine the type of connection (getting a file or retrieving -- a file) and call the appropriate function. */ void processConnection(int socket, char *ip, int port) { int transferSocket = 0; char *buffer = (char*)malloc(sizeof(char) * BUFFER_LENGTH); // Read data from the client readData(&socket, buffer, BUFFER_LENGTH); printf("Filename is %s and the command is %d\n", buffer + 1, buffer[0]); // Close the command socket close(socket); // Connect to the client createTransferSocket(&transferSocket); if (connectToServer(&port, &transferSocket, ip) == -1) { systemFatal("Unable To Connect To Client"); } printf("Connected to Client: %s\n", ip); switch ((int)buffer[0]) { case GET_FILE: // Add 1 to buffer to move past the control byte printf("Sending %s to client now...\n", buffer + 1); sendFile(transferSocket, buffer + 1); break; case SEND_FILE: // Add 1 to buffer to move past the control byte printf("Getting %s from client now...\n", buffer + 1); getFile(transferSocket, buffer + 1); printf("Getting %s successful.\n", buffer + 1); break; case REQUEST_LIST: break; } // Free local variables and sockets printf("Closing client connection\n"); free(buffer); close(transferSocket); }
void * startReconnectThread(void *url) { reconnectLoop = 1; reconnectThreadRunning = 1; while (reconnectLoop) { time_t currentTime; currentTime = time(¤tTime); for(int i = 0; i < gMain.gNumEncoders; i++) { if(g[i]->forcedDisconnect) { LogMessage(g[i], LOG_DEBUG, "Reconnecting disconnected encoder."); int timeout = getReconnectSecs(g[i]); int timediff = currentTime - g[i]->forcedDisconnectSecs; if(timediff > timeout) { g[i]->forcedDisconnect = false; if(!g[i]->weareconnected) { setForceStop(g[i], 0); if(!connectToServer(g[i])) { g[i]->forcedDisconnect = true; g[i]->forcedDisconnectSecs = time(&(g[i]->forcedDisconnectSecs)); } LogMessage(g[i], LOG_DEBUG, "Done Reconnecting disconnected encoder."); } } else { char buf[255] = ""; sprintf(buf, "Connecting in %d seconds", timeout - timediff); outputStatusCallback(g[i], buf); } } } #ifdef WIN32 Sleep(1000); #else sleep(1); #endif } reconnectThreadRunning = 0; return(NULL); }
// Performs a connect retry (or hardware reset) if not connected bool ESP8266wifi::watchdog() { if (serverRetries >= SERVER_CONNECT_RETRIES_BEFORE_HW_RESET) { // give up, do a hardware reset return restart(); } if (flags.serverConfigured && !flags.connectedToServer) { serverRetries++; if (flags.apConfigured && !isConnectedToAP()) { if (!connectToAP()) { // wait a bit longer, then check again delay(2000); if (!isConnectedToAP()) { return restart(); } } } return connectToServer(); } return true; }
MainController::MainController(ProjectorWindow &target) : ProjectorController(target), m_net(new ProjectorNet(this)), m_stageDataCounter(0), m_connected(false), m_view(TemplateManager::INDEX), m_activeQuestionIndex(0), m_activeRound (0) { connect(m_net, SIGNAL(onConnect()), this, SLOT(onConnect())); connect(m_net, SIGNAL(onContestState(ushort,CONTEST_STATUS)), this, SLOT(onContestState(ushort,CONTEST_STATUS))); connect(m_net, SIGNAL(onContestTime(ushort)), this, SLOT(onContestTime(ushort))); connect(m_net, SIGNAL(onDisconnect()), this, SLOT(onDisconnect())); connect(m_net, SIGNAL(onError(QString)), this, SLOT(onError(QString))); connect(m_net, SIGNAL(onQuestionState(ushort,ushort,QUESTION_STATUS)), this, SLOT(onQuestionState(ushort,ushort,QUESTION_STATUS))); connect(m_net, SIGNAL(onShowAnswer()), this, SLOT(onShowAnswer())); connect(m_net, SIGNAL(onHideAnswer()), this, SLOT(onHideAnswer())); connect(m_net, SIGNAL(onShowContestRanks(vector<RankData>)), this, SLOT(onShowContestRanks(vector<RankData>))); connect(m_net, SIGNAL(onShowContestTime()), this, SLOT(onShowContestTime())); connect(m_net, SIGNAL(onShowMainScreen()), this, SLOT(onShowMainScreen())); connect(m_net, SIGNAL(onStageData(ushort, QString)), this, SLOT(onStageData(ushort, QString))); connect(m_net, SIGNAL(onNumRounds(ushort)), this, SLOT(onRoundsReceived(ushort))); QTimer::singleShot(CONNECT_DELAY, this, SLOT(connectToServer())); }
void main() { networkSetup(); if (create_connect())exit(0); sleep(1); create_full(); connectToServer(); //control() in new thread int unused = 0; pthread_t controlThread; int threadError = pthread_create (&controlThread,NULL,control, &unused); if(threadError) { printf("thread could not be started! \nerror: %d \nexiting program!\n",threadError); exit(0); } serverCommunication(); }
// --- Do network communications --- void NetworkClient::communicate(float frameTime) { AnnDebug() << "Com"; if(clientConnected) getInfoFromServer(); // Get game state from server // Calculate elapsed time for network communications /*netTime += frameTime; if(netTime < netNS::NET_TIMER) // if not time to communicate*/ //return; if(tryToConnect) connectToServer(); // Attempt to connect to game server else if(clientConnected) { AnnDebug() << "Should transmit data here"; checkNetworkTimeout(); // check for disconnect from server sendInfoToServer(); // } netTime -= netNS::NET_TIMER; }
int main(int argc, char **argv) { char buffer[MAXLINE]; // // Check for host name and port number. // if (argc != 3) { fprintf(stderr,"usage: %s <host> <port>\n", argv[0]); exit(0); } // // Connect to the server. // int server = connectToServer(argv[1],atoi(argv[2])); printf("Welcome to the remote SOLITAIRE game for MATH 442.\n\n"); printf("Here is a key of possible card plays you can make:\n"); printf("\tplay <face><suit> - throw a card onto an arena pile in the center.\n"); printf("\tmove k<suit> - move a king onto an empty pile.\n"); printf("\tmove <face><suit> <face><suit>- move a card, putting it on top of another card.\n"); printf("\tdraw - draw and overturn the next card, placing it on the discard pile.\n"); printf("where <face> is one of a,2,3,...,9,t,j,q,k and <suit> is one of d,c,s,h.\n"); // // Send a series of solitaire play commands. // while (1) { printf("\nEnter a card play: "); fgets(buffer,MAXLINE,stdin); write(server,buffer,strlen(buffer)+1); if (receiveAck(server)) { printf("Done!\n"); } else { printf("That play wasn't made.\n"); } } }
void EtherIPC::init() { fConnectAttempts = 0; if ( fStarting <= 0 ) { // try to connect without starting geth EtherLog::logMsg("Etherwall starting", LS_Info); fStarting = 1; emit startingChanged(fStarting); return connectToServer(); } const QSettings settings; const QString progStr = settings.value("geth/path", DefaultGethPath()).toString(); const QString argStr = settings.value("geth/args", DefaultGethArgs).toString(); const QString ddStr = settings.value("geth/datadir", DefaultDataDir).toString(); QStringList args = (argStr + " --datadir " + ddStr).split(' ', QString::SkipEmptyParts); bool testnet = settings.value("geth/testnet", false).toBool(); if ( testnet ) { args.append("--testnet"); } bool hardfork = settings.value("geth/hardfork", true).toBool(); if ( hardfork ) { args.append("--support-dao-fork"); } else { args.append("--oppose-dao-fork"); } QFileInfo info(progStr); if ( !info.exists() || !info.isExecutable() ) { fStarting = -1; emit startingChanged(-1); setError("Could not find Geth. Please check Geth path and try again."); return bail(); } EtherLog::logMsg("Geth starting " + progStr + " " + args.join(" "), LS_Info); fStarting = 2; fGethLog.attach(&fGeth); fGeth.start(progStr, args); emit startingChanged(0); }
/* -- FUNCTION: initConnection -- -- DATE: September 23, 2011 -- -- REVISIONS: -- -- DESIGNER: Karl Castillo -- -- PROGRAMMER: Karl Castillo -- -- INTERFACE: int initConnection(int port, const char* ip) -- port - the port the client will connect to to the server -- ip - ip address of the server -- -- RETURNS: int - the new socket created -- -- NOTES: -- This function will create the socket, set reuse and connect to the server. */ int initConnection(int port, const char* ip) { int socket; // Creating Socket if((socket = tcpSocket()) == -1) { systemFatal("Error Creating Socket"); } // Setting Socket to Reuse if(setReuse(&socket) == -1) { systemFatal("Error Set Socket Reuse"); } // Connect to transfer server if(connectToServer(&port, &socket, ip) == -1) { systemFatal("Cannot Connect to server"); } return socket; }
void SQLToolWidget::handleDatabaseDropped(const QString &dbname) { try { //Closing tabs related to the database to be dropped for(int i=0; i < databases_tbw->count(); i++) { if(databases_tbw->tabText(i).remove('&') == dbname) { closeDatabaseExplorer(i); i=-1; } } connectToServer(); } catch(Exception &e) { throw Exception(e.getErrorMessage(), e.getErrorType(),__PRETTY_FUNCTION__,__FILE__,__LINE__, &e); } }
bool IRC::receiveMessage(uint8_t MSG_ID, uint8_t callingThreadID, void* cdata) { bool lRetval = false; //std::cerr << "IRCthread msg received." << std::endl; if(MSG_THREAD_START_WORK == MSG_ID) { std::cerr << "Begin connect to server." << std::endl; lRetval = connectToServer(); std::cerr << "Connected to server as \"" << mMyNick << "\"" << std::endl; if(cdata) delete(static_cast<ClientQueryData*>(cdata)); } else if(MSG_QUERY_REPLY == MSG_ID) { //handleReply(static_cast<ClientQueryData*>(cdata)); doCallback(cdata); //delete(cdata); } return(lRetval); }
void Client::btnConnectOnClick() { if (connectionState == ConnectionState::STATE_DISCONNECTED) { if ((serverConfiguration == nullptr) || (clientConfiguration == nullptr)) { QMessageBox::warning(this, "Can not connect", "Please choose a valid client configuration file first."); return; } setupProtocolClient(); ui.btnConnect->setEnabled(false); ui.btnConnect->setText("Connecting..."); QTimer::singleShot(0, protocolClient, SLOT(connectToServer())); } else if (connectionState == ConnectionState::STATE_CONNECTING) { // No click should be possible in this state ui.btnConnect->setEnabled(false); } else if (connectionState == ConnectionState::STATE_CONNECTED) { ui.btnConnect->setEnabled(false); ui.btnConnect->setText("Disconnecting..."); QTimer::singleShot(0, protocolClient, SLOT(disconnectFromServer())); } }
int Client::rpcCall(const std::string& fun, int* argTypes, void** args) const { FunctionSignature signature(fun, argTypes); int serverSocket = connectToServer(signature); if (serverSocket < 0) { return serverSocket; } Connection conn(serverSocket); FunctionCall functionCall(std::move(signature), args); if (conn.send(Message::Type::CALL, functionCall.serialize()) < 0) { conn.close(); return -1; } Message message; while (true) { int r = conn.read(&message); if (r < 0) { conn.close(); return -1; } else if (r > 0) { // Done conn.close(); break; } } if (message.type != Message::Type::CALL) { // Error return -1; } // Now we must deserialize the message auto callReturn = FunctionCall::deserialize(message); // Got the response back callReturn.writeDataTo(args); return 0; }
int main(int argc, const char * argv[]) { char commandBuffer[512]; ssize_t commandLength; int socketHandle = -1; int countDown = MAX_ATTEMPTS_WITHOUT_STATUS; while (true) { if (socketHandle < 0) { socketHandle = connectToServer(SERVER_ADDRESS, SERVER_PORT); } if (socketConnected(socketHandle)) { int available = dataAvailable(socketHandle, 30); if (available > 0) { commandLength = receiveData(socketHandle, commandBuffer, sizeof(commandBuffer)); if (commandLength > 0) { countDown = MAX_ATTEMPTS_WITHOUT_STATUS; std::cout << "Received: " << commandBuffer << std::endl; handleCommand(socketHandle, commandBuffer, commandLength); } } else if ((countDown <= 0) || (available < 0)) { // socket must have broke, let's close and re-attempt close(socketHandle); socketHandle = -1; countDown = MAX_ATTEMPTS_WITHOUT_STATUS; } else { countDown -= 1; } } else { sleep(20); } } return 0; }
int main( int argc, const char* argv[] ) { header(3, 1, false); //============================ // SSL init SSL_library_init(); SSL_load_error_strings(); ERR_load_BIO_strings(); OpenSSL_add_all_algorithms(); // ============== SSL init // // Verify args if (argc !=5) { printf("Usage:\n"); printf("\t ./client --serverAddress=127.0.0.1 --port=1234 --send ./filename\n"); printf("\t ./client --serverAddress=127.0.0.1 --port=1234 --recieve ./filename\n"); exit(54); } char* serverhost = (char*) argv[1]; char* port = (char*) argv[2]; char* transType = (char*) argv[3]; char* file = (char*) argv[4]; serverhost = strrchr(serverhost, '=') + sizeof(char); port = strrchr(port, '=') + sizeof(char); transType = strrchr(transType, '-') + sizeof(char); printf("server: %s\n", serverhost); printf("port: %s\n", port); printf("transType: %s\n", transType); printf("file: %s\n", file); // seed for random numbers srand(time(0)); // connect to server connectToServer(serverhost,port,transType, file); printf("Client application is exiting.\nGood Bye!\n"); return 0; }
int main(int argc, char** argv){ if (argc != 2){ printf("Pemakaian: ./client <server ip>\n"); } else{ connectToServer(argv[1]); // membuka koneksi ke server, jika gagal keluar dengan kode 1 active = true; header(); thread menu(start); thread msgrec(recieveMessage); menu.join(); msgrec.join(); } return 0; }
/* * check_for_prepared_transactions() * * Make sure there are no prepared transactions because the storage format * might have changed. */ static void check_for_prepared_transactions(ClusterInfo *cluster) { PGresult *res; PGconn *conn = connectToServer(cluster, "template1"); prep_status("Checking for prepared transactions"); res = executeQueryOrDie(conn, "SELECT * " "FROM pg_catalog.pg_prepared_xacts"); if (PQntuples(res) != 0) pg_fatal("The %s cluster contains prepared transactions\n", CLUSTER_NAME(cluster)); PQclear(res); PQfinish(conn); check_ok(); }
/* * get_pg_database_relfilenode() * * Retrieves the relfilenode for a few system-catalog tables. We need these * relfilenodes later in the upgrade process. */ void get_pg_database_relfilenode(ClusterInfo *cluster) { PGconn *conn = connectToServer(cluster, "template1"); PGresult *res; int i_relfile; res = executeQueryOrDie(conn, "SELECT c.relname, c.relfilenode " "FROM pg_catalog.pg_class c, " " pg_catalog.pg_namespace n " "WHERE c.relnamespace = n.oid AND " " n.nspname = 'pg_catalog' AND " " c.relname = 'pg_database' " "ORDER BY c.relname"); i_relfile = PQfnumber(res, "relfilenode"); cluster->pg_database_oid = atooid(PQgetvalue(res, 0, i_relfile)); PQclear(res); PQfinish(conn); }
void QXmppClient::setClientPresence(const QXmppPresence& presence) { d->clientPresence = presence; d->addProperCapability(d->clientPresence); if (presence.type() == QXmppPresence::Unavailable) { // cancel reconnection d->reconnectionTimer->stop(); // NOTE: we can't call disconnect() because it alters // the client presence if (d->stream->isConnected()) sendPacket(d->clientPresence); d->stream->disconnectFromHost(); } else if (d->stream->isConnected()) sendPacket(d->clientPresence); else connectToServer(d->stream->configuration(), presence); }
MyIRC::MyIRC(QWidget *mainWindow) { this->mainWindow = static_cast<test*>(mainWindow); //widget community. this->session = new MySession(this); this->controller = new WindowController(this); QPushButton *actConnect = new QPushButton("connect", mainWindow); connect(actConnect, SIGNAL(clicked()), this, SLOT(connectToServer())); actConnect->move(760, 0); //this->mainWindow->getUi()->mainToolBar->addAction(actConnect); QPushButton *actDisConnect = new QPushButton("Disconnect", mainWindow); connect(actDisConnect, SIGNAL(clicked()), this, SLOT(disconnectFromServer())); //this->mainWindow->getUi()->mainToolBar->addAction(actDisConnect); actDisConnect->move(834, 0); QPushButton *actSetNickname = new QPushButton("Set Nickname", mainWindow); connect(actSetNickname, SIGNAL(clicked()), this, SLOT(setNickname())); actSetNickname->move(930, 0); //this->mainWindow->getUi()->mainToolBar->addAction(actSetNickname); }