Network::Network(const QString &host, quint16 port) : commandStarted(false) { if (port == 0) { //Default argument, not worth going further } else { connectToHost(host, port); } connect(this, SIGNAL(readyRead()), SLOT(onReceipt())); }
void OftSocket::directConnect(const QHostAddress &addr, quint16 port) { m_state = ReadHeader; connectToHost(addr, port); m_clientPort = port; m_timer.start(); debug().nospace() << "Trying to establish a direct connection to " << addr.toString().toLocal8Bit().constData() << ":" << port; }
void ZMClient::restartConnection() { // Reset the flag m_zmclientReady = false; m_bConnected = false; m_server_unavailable = false; // Retry to connect. . . Maybe the user restarted mythzmserver? connectToHost(m_hostname, m_port); }
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); ui->gameBox->setEnabled(FALSE); connect(ui->clientButton, SIGNAL(released()), this, SLOT(connectToHost())); connect(ui->serverButton, SIGNAL(released()), this, SLOT(runServer())); moves = 0; }
void ApcUpsMon::requestEvents() { if (socket.state() == QAbstractSocket::ConnectedState) { socket.putChar('\0'); socket.putChar('\x06'); socket.write("events"); } else { // We're not connected, try and reconnect? connectToHost(); } }
void Connection::connectToServer() { Q_ASSERT(!m_host.isEmpty()); Q_ASSERT(m_port); connect(this, SIGNAL(connected()), SLOT(onConnected()), Qt::UniqueConnection); connect(this, SIGNAL(disconnected()), SLOT(onDisconnected()), Qt::UniqueConnection); connect(this, SIGNAL(readyRead()), SLOT(onReadyRead()), Qt::UniqueConnection); connect(this, SIGNAL(error(QAbstractSocket::SocketError)), SLOT(onError(QAbstractSocket::SocketError)), Qt::UniqueConnection); connectToHost(m_host, m_port); }
void *connect(void *data){ struct program_data *tData; tData = (struct program_data*) data; while ((*tData).hasQuit == 0){ connectToHost((*tData).ipInput); sleep(10);//prevents spamming the network if server is down } return NULL; }
Server::Server(QObject * parent) : QObject(parent) { _server = new QTcpServer(this); connect(_server, SIGNAL(newConnection()), SLOT(connected())); if(connectToHost(QHostAddress::Any, 8081)) { // Pokud jsme tady, server jeste neni pripojen k Log!!! syslog(LOG_INFO, "Server is listening..."); } else { syslog(LOG_ERR, "Could not listen on given port!"); } }
/*! If there's a connection activity on the socket, process it. Then notify our parent if there really was activity. */ void QNativeSocketEngine::connectionNotification() { Q_D(QNativeSocketEngine); Q_ASSERT(state() == QAbstractSocket::ConnectingState); connectToHost(d->peerAddress, d->peerPort); if (state() != QAbstractSocket::ConnectingState) { // we changed states QAbstractSocketEngine::connectionNotification(); } }
MainWindow::MainWindow(Socket *connection, QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow), connection(connection) { ui->setupUi(this); /* Disable unavailable offline control */ ui->configurationWidget->setDisabled(true); ui->controlWidget->setDisabled(true); ui->PiecesDock->setDisabled(true); ui->stopButton->setDisabled(true); ui->resumeButton->setDisabled(true); /* Connection/Disconnection notification */ connect(connection, SIGNAL(connected()), this, SLOT(connectionNotify())); connect(connection, SIGNAL(disconnected()), this, SLOT(disconnectionNotify())); /* Received logLine */ connect(connection, SIGNAL(gotLog(QString)), this, SLOT(appendLog(QString))); /* Received Boxed info */ connect(connection, SIGNAL(gotAccepted(int)), this, SLOT(addAccepted(int))); connect(connection, SIGNAL(gotRejected(int)), this, SLOT(addRejected(int))); /* Received Error / Warning */ connect(connection, SIGNAL(gotError(int)), this, SLOT(errorNotify(int))); //connect(connection, SIGNAL(gotWarning(int)), this, SLOT(warningNotify(int))); /* Connection button */ connect(ui->ConnectionButton, SIGNAL(clicked()), this, SLOT(connectToHost())); /* Send configuration data button */ connect(ui->sendConfigButton, SIGNAL(clicked()), this, SLOT(sendConfig())); /* Actions button : Lauch / Resume / Stop */ connect(ui->launchButton, SIGNAL(clicked()), this, SLOT(launch())); connect(ui->resumeButton, SIGNAL(clicked()), this, SLOT(resume())); connect(ui->stopButton, SIGNAL(clicked()), this, SLOT(stop())); /* Refresh time display */ connect(&timer, SIGNAL(timeout()), this, SLOT(displayTime())); timer.start(50); }
// Have a socket error, set m_errorString and propagate // signal void ApcUpsMon::socketError(QAbstractSocket::SocketError) { m_errorString = socket.errorString(); if (socket.state() != QAbstractSocket::ConnectedState) { // Attempt to reconnect in two timer intervals or, // failing that, ten seconds QTimer::singleShot((timer.interval() ? timer.interval() : 10000), this, SLOT(connectToHost())); } emit haveError(m_errorString); }
/*! Waits for \a msecs milliseconds or until the socket is ready for writing. If \a timedOut is not 0 and \a msecs milliseconds have passed, the value of \a timedOut is set to true. Returns true if data is available for writing; otherwise returns false. This is a blocking function call; its use is disadvised in a single threaded application, as the whole thread will stop responding until the function returns. waitForWrite() is most useful when there is no event loop available. The general approach is to create a QSocketNotifier, passing the socket descriptor returned by socketDescriptor() to its constructor. */ bool QNativeSocketEngine::waitForWrite(int msecs, bool *timedOut) { Q_D(QNativeSocketEngine); Q_CHECK_VALID_SOCKETLAYER(QNativeSocketEngine::waitForWrite(), false); Q_CHECK_NOT_STATE(QNativeSocketEngine::waitForWrite(), QAbstractSocket::UnconnectedState, false); if (timedOut) *timedOut = false; int ret = d->nativeSelect(msecs, false); // On Windows, the socket is in connected state if a call to // select(writable) is successful. In this case we should not // issue a second call to WSAConnect() #if defined (Q_WS_WIN) if (ret > 0) { setState(QAbstractSocket::ConnectedState); d_func()->fetchConnectionParameters(); return true; } else { int value = 0; int valueSize = sizeof(value); if (::getsockopt(d->socketDescriptor, SOL_SOCKET, SO_ERROR, (char *) &value, &valueSize) == 0) { if (value == WSAECONNREFUSED) { d->setError(QAbstractSocket::ConnectionRefusedError, QNativeSocketEnginePrivate::ConnectionRefusedErrorString); d->socketState = QAbstractSocket::UnconnectedState; return false; } else if (value == WSAETIMEDOUT) { d->setError(QAbstractSocket::NetworkError, QNativeSocketEnginePrivate::ConnectionTimeOutErrorString); d->socketState = QAbstractSocket::UnconnectedState; return false; } else if (value == WSAEHOSTUNREACH) { d->setError(QAbstractSocket::NetworkError, QNativeSocketEnginePrivate::HostUnreachableErrorString); d->socketState = QAbstractSocket::UnconnectedState; return false; } } } #endif if (ret == 0) { if (timedOut) *timedOut = true; d->setError(QAbstractSocket::SocketTimeoutError, QNativeSocketEnginePrivate::TimeOutErrorString); d->hasSetSocketError = false; // A timeout error is temporary in waitFor functions return false; } else if (state() == QAbstractSocket::ConnectingState) { connectToHost(d->peerAddress, d->peerPort); } return ret > 0; }
bool KMSmtpClient::login() { //Check out state. if((!isConnected()) && (!connectToHost())) { //Means socket is still not connected to server or already login. return false; } //Check auth method. if(authMethod()==AuthPlain) { //Sending command: AUTH PLAIN base64('\0' + username + '\0' + password) sendMessage("AUTH PLAIN " + QByteArray().append((char)0x00) .append(userName()).append((char)0x00) .append(password()).toBase64()); // The response code needs to be 235. if(!waitAndCheckResponse(235, ServerError)) { //Failed to login. return false; } //Mission complete. return true; } //Then the method should be auth login. // Sending command: AUTH LOGIN sendMessage("AUTH LOGIN"); //The response code needs to be 334. if(!waitAndCheckResponse(334, AuthenticationFailedError)) { //Failed to login. return false; } // Send the username in base64 sendMessage(QByteArray().append(userName()).toBase64()); //The response code needs to be 334. if(!waitAndCheckResponse(334, AuthenticationFailedError)) { //Failed to login. return false; } // Send the password in base64 sendMessage(QByteArray().append(password()).toBase64()); //If the response is not 235 then the authentication was faild if(!waitAndCheckResponse(235, AuthenticationFailedError)) { //Failed to login. return false; } //Mission compelte. return true; }
void enviarRespuesta(char* hostname,char* respuesta) { char request[1000]; setupSocket(hostname); connectToHost(hostname); sprintf(request,"GET /index.php?r=juego/respuesta&tokenSolicitud=%s&solucion=%s HTTP/1.1\r\nHost: %s\r\n\r\n",tokenSolicitud,respuesta,hostname); //http://hornero.fi.uncoma.edu.ar/index.php?r=juego/respuesta&&tokenSolicitud=76d7cadd3df99e06ae8c4aa580ca6900&solucion=-5933 printf("\nse envia request: %s\n", request); if (send(sock, request, sizeof(request), 0) != (int)sizeof(request)) { printf( "Error sending request." ); exit(1); } getBuffer(); }
void TcpClient::tryConnectToHost(const QString &host, int port) { setServerPort(port); if (host == zeroHost) { if (!findLocalIpv4InterfaceData()) { return; } } else { if (connectToHost(host, port)) { setServerIp(host); } } }
void enviarSolicitud(char* hostname, char* token,char* problema) { char request[1000]; setupSocket(hostname); connectToHost(hostname); sprintf(request,"GET /index.php?r=juego/solicitud&token=%s&problema=%s HTTP/1.1\r\nHost: %s\r\n\r\n",token,problema,hostname); //printf("se envia request: %s", request); if (send(sock, request, sizeof(request), 0) != (int)sizeof(request)) { printf( "Error sending request." ); exit(1); } getBuffer(); }
bool ftpInterface::uploadFile(QString fileName,QString fixFilename,bool deleteSource) { delSrc=deleteSource; // progress->show(); aborting=FALSE; addToLog("FTP uploadFile",LOGFTP); if ( fileName.isNull() ) return FALSE; ftpDone=TRUE; if(isUnconnected()) { ftpDone=FALSE; connectToHost(); } while(!ftpDone) { if(aborting) return FALSE; qApp->processEvents(); } sourceFn=new QFile(fileName); if ( !sourceFn->open( QIODevice::ReadOnly ) ) { // QMessageBox::critical( 0, tr("Upload error"), // tr("Can't open file '%1' for reading.").arg(fileName) ); delete sourceFn; sourceFn=NULL; return FALSE; } QFileInfo fi( fileName ); QFileInfo fin(fixFilename); addToLog(QString("FTP bytes: %1").arg(sourceFn->size()),LOGFTP); ftpDone=FALSE; int id=ftp->put( sourceFn, fi.fileName(),QFtp::Binary); addToLog(QString("FTP put file id: %1").arg(id),LOGFTP); while(!ftpDone) { if(aborting) return FALSE; qApp->processEvents(); } if(!fixFilename.isEmpty()) { ftp->rename(fi.fileName(),fin.fileName()); } addToLog("FTP starting progress",LOGFTP); //progress->exec(); // ### takes a lot of time!!! return TRUE; }
void Benchmark::connectToHost() { if (m_count < m_usersCount) { BenchmarkClient *client; if (m_authIn.size() > m_count) client = new BenchmarkClient(m_authIn.at(m_count).toMap(), this); else client = new BenchmarkClient(m_nickPrefix + QString::number(m_count), this); connect(client->io(), SIGNAL(clientStateChanged(int,int)), SLOT(clientStateChanged(int,int))); client->open(m_serverAddr); // client->setNick(m_nickPrefix + QString::number(m_count)); // client->setCookieAuth(false); // client->openUrl(m_serverAddr); // QSettings settings(m_chatConf, QSettings::IniFormat, this); // settings.setIniCodec("UTF-8"); // settings.setValue("Profile/Nick", m_nickPrefix + QString::number(m_count)); // // QProcess *chat = new QProcess(this); // m_process.append(chat); // // chat->start(m_chatFile); // chat->waitForStarted(); // AbstractProfile *profile = new AbstractProfile(); // profile->setNick(m_nickPrefix + QString::number(m_count)); // connect(this, SIGNAL(finished()), profile, SLOT(deleteLater())); // ClientService *service = new ClientService(profile, m_network); // connect(this, SIGNAL(finished()), service, SLOT(deleteLater())); #if !defined(BENCHMARK_NO_UI) // connect(service, SIGNAL(accessGranted(QString,QString,quint16)), SLOT(accessGranted(QString,QString,quint16))); // connect(service, SIGNAL(accessDenied(quint16)), SLOT(accessDenied(quint16))); // connect(service, SIGNAL(syncUsersEnd()), SLOT(syncUsersEnd())); // connect(service, SIGNAL(unconnected(bool)), SLOT(unconnected())); emit started(++m_count); #else ++m_count; #endif // msleep(m_connectInterval); // connectToHost(); // service->connectToHost(); QTimer::singleShot(m_connectInterval, this, SLOT(connectToHost())); }
bool CTcpClient::Connect2Server( const QHostAddress &hostAddr, quint16 nPort ) { svrAddr = hostAddr; nSvrPort = nPort; try { connectToHost( svrAddr, nSvrPort ); } catch ( ... ) { int n = 0; n++; return false; } return true; }
Response Client::get(const string &path) { connectToHost(); std::ostringstream request_stream; request_stream << "GET " << path << " HTTP/1.1\r\n"; request_stream << "Host: " << host_.hostName() << "\r\n"; request_stream << "Accept: */* \r\n"; if (x_api_key_ != "") request_stream << "X-Api-Key: " << x_api_key_ << "\r\n"; if (access_token_ != "") request_stream << "Authorization: Bearer " << access_token_ << "\r\n"; request_stream << "Connection: close \r\n\r\n"; // close socket connection after get all response return getResponse(request_stream.str()); }
void FtpDownloader::download(const QUrl &url, QIODevice* dev) { url_ = url; dev_ = dev; QString server = url_.host(); if (server.isEmpty()) { server = url_.toString(); } int port = 21; if (url_.port() != -1) { port = url_.port(); } connectToHost(server, port); }
// IO members void EventHandler::connectDevice(const QString &args) { // Connect a particular session's sockets. if (!args.isEmpty()) { // Update the host and port QStringList list = args.split(QRegExp("[:\\s]+"), QString::SkipEmptyParts); qDebug() << list << list.size(); if (list.size() == 2) { _socketReader->host(list.at(0)); _socketReader->port(list.at(1).toInt()); } } emit connectToHost(); }
bool ftpInterface::downloadFile(QString sourceFileName,QString destinationFilename) { delSrc=FALSE; aborting=FALSE; addToLog("FTP downloadFile",LOGFTP); QFile *destFn; destFn=new QFile(destinationFilename); if(!destFn->open(QIODevice::WriteOnly)) { addToLog(QString("FTP unable to open destinationFilename %1").arg(destinationFilename),LOGFTP); return FALSE; } if (sourceFileName.isNull() ) return FALSE; ftpDone=TRUE; if(isUnconnected()) { ftpDone=FALSE; connectToHost(); } while(!ftpDone) { if(aborting) return FALSE; qApp->processEvents(); } if(isUnconnected()) { addToLog("FTP connection failed",LOGFTP); return FALSE; } ftpDone=FALSE; ftpCommandSuccess=FALSE; ftp->get( sourceFileName, destFn,QFtp::Binary); addToLog(QString("FTP get sourcefile %1 destination %2").arg(sourceFileName).arg(destFn->fileName()),LOGFTP); while(!ftpDone) { if(aborting) return FALSE; qApp->processEvents(); } if(!ftpCommandSuccess) return FALSE; addToLog(QString("FTP file: %1 bytes: %2").arg(destinationFilename).arg(QFile(destinationFilename).size()),LOGFTP); return TRUE; }
int connectToClient(char *hostName, char *port) { //check if the host is trying to connect to itself if ((stringEquals(hostName, myHostName) || stringEquals(hostName, myIpAddress)) && (stringEquals(port, myListenerPort))) { printf("You can't connect to yourself.\n"); return -1; } //Check if hostname/ip and port is registered to server if (!isHostPresent(peerList, hostName, port)) { printf("The client you are trying to connect to is not registered with the server.\n"); return -1; } //duplicate connection if (isHostPresent(connectionList, hostName, port)) { printf("You are already connected to %s/%s.\n", hostName, port); return -1; } //check if the user entered a ipAddress or hostName if (stringEquals(getIpfromHost(hostName), hostName)) { //if true the user entered an ipaddress hostName = getHostFromIp(hostName); } //printf("Connecting to %s/%s.\n", hostName, port); int clientSockfd = connectToHost(hostName, port); //"localhost" should be hostName #needtomodify if (clientSockfd == -1) { fprintf(stderr, "Error connecting to client\n"); } else { //add the client to the connectionList struct host *client = (struct host *) malloc(sizeof(struct host)); client->id = connectionIdGenerator++; client->sockfd = clientSockfd; client->ipAddress = getIpfromHost(hostName); client->hostName = hostName; client->port = port; addNode(&connectionList, client); printf("Connected to %s/%s\n", client->hostName, client->port); } return 0; }
void Benchmark::start() { QSettings settings(QCoreApplication::applicationDirPath() + "/benchmark.conf", QSettings::IniFormat, this); settings.setIniCodec("UTF-8"); m_connectInterval = settings.value("ConnectInterval", m_connectInterval).toInt(); m_usersCount = settings.value("UsersCount", m_usersCount).toInt(); m_nickPrefix = settings.value("NickPrefix", m_nickPrefix).toString(); m_serverAddr = settings.value("Url", m_serverAddr).toString(); QFile file(QCoreApplication::applicationDirPath() + "/benchmark.cache"); if (file.open(QFile::ReadOnly)) { QVariantMap cache = JSON::parse(file.readAll()).toMap(); m_authIn = cache.value("auth").toList(); } connectToHost(); }
FrostbiteClient::FrostbiteClient(ServerEntry *serverEntry, FrostbiteCommandHandler *commandHandler, QObject *parent) : Client(serverEntry, parent), connection(new FrostbiteConnection(commandHandler, this)), commandHandler(commandHandler) { connectToHost(); // Connection connect(connection, &Connection::onConnected, this, &FrostbiteClient::onConnected); connect(connection, &Connection::onDisconnected, this, &FrostbiteClient::onDisconnected); // Commands connect(commandHandler, static_cast<void (FrostbiteCommandHandler::*)(const QByteArray&)>(&FrostbiteCommandHandler::onLoginHashedCommand), this, static_cast<void (FrostbiteClient::*)(const QByteArray&)>(&FrostbiteClient::onLoginHashedCommand)); connect(commandHandler, static_cast<void (FrostbiteCommandHandler::*)(bool)>(&FrostbiteCommandHandler::onLoginHashedCommand), this, static_cast<void (FrostbiteClient::*)(bool)>(&FrostbiteClient::onLoginHashedCommand)); connect(commandHandler, &FrostbiteCommandHandler::onVersionCommand, this, &FrostbiteClient::onVersionCommand); }
qSslChat :: qSslChat() { setupUi(this); messageList -> setDisabled(true); messageList -> setAcceptDrops(true); msgEdit -> setDisabled(true); sendButton -> setDisabled(true); smileyButton -> setDisabled(true); cinfoButton -> setDisabled(true); portBox -> setRange(1024,65535); portBox -> setValue(7752); setWindowTitle("Buddies SSL Chat"); setWindowIcon(QIcon(":/icons/Logo.png")); mode=0; server=0; cinfoButton -> setIcon(QIcon(":/icons/encrypted.png")); cinfoButton -> setIconSize(QSize(20,20)); cinfoButton -> setToolTip(tr("Display certificate info")); connect(cinfoButton,SIGNAL(clicked()),this,SLOT(displayCertificateInfo())); smileyButton -> setIcon(QIcon(":/emoticons/01.gif")); smileyButton -> setIconSize(QSize(20,20)); connect(smileyButton,SIGNAL(clicked()),this,SLOT(selectSmiley())); emoSelector = new EmoticonSelector(this); emoSelector -> hide(); emoSelector -> alignTo(smileyButton); connect(emoSelector,SIGNAL(smileySelected(QString,QString)),this,SLOT(insertSmiley(QString,QString))); tableFormat.setBorder(0); //systray = new systemTray(this); addAnimations(); QTextCodec::setCodecForCStrings(QTextCodec::codecForName("UTF8")); QTextCodec::setCodecForTr(QTextCodec::codecForName("UTF8")); connect(hostButton,SIGNAL(clicked()),this,SLOT(hostConnection())); connect(connectButton,SIGNAL(clicked()),this,SLOT(connectToHost())); connect(disconnectButton,SIGNAL(clicked()),this,SLOT(endConnection())); connect(messageList,SIGNAL(fileSendInitiated(QString,int,int)),this,SLOT(sendFile(QString,int,int))); }
Slave::Slave( const Ipc::Id &masterId, const Ipc::Id &slaveId ) : QTcpSocket(), m_slaveId( slaveId ), m_pingTimer( this ), m_lastPingResponse( QTime::currentTime() ) { connect( this, SIGNAL( readyRead() ), this, SLOT( receiveMessage() ) ); connect( this, SIGNAL( error( QAbstractSocket::SocketError ) ), QCoreApplication::instance(), SLOT( quit() ) ); m_pingTimer.setInterval( 1000 ); connect( &m_pingTimer, SIGNAL( timeout() ), this, SLOT( masterPing() ) ); connect( this, SIGNAL( connected() ), &m_pingTimer, SLOT( start() ) ); connectToHost( QHostAddress::LocalHost, masterId.toInt() ); }
void NetworkPinger::pingOnce() { auto _conn=new QTcpSocket(nullptr); _conn->connectToHost("216.58.219.36", 80); //_conn->connectToHost("74.125.224.83", 80); if (!_conn->waitForConnected(500)) { //qDebug()<<"Not connected" <<_conn->error(); if (!isPaused()) emit connectionHit(false); } else { //qDebug()<<"Connected!"; if (!isPaused()) emit connectionHit(true); } delete _conn; }
bool TcpClient::findLocalIpv4InterfaceData() { //Firstly get IP and try to find server on local host foreach (const QHostAddress &address, QNetworkInterface::allAddresses()) { if (!address.isNull() && address.protocol() == QAbstractSocket::IPv4Protocol && address != QHostAddress(QHostAddress::LocalHost)) { m_localHost = address.toString(); if (connectToHost(address.toString(), m_port)) { setServerIp(address.toString()); return true; } else if (serachServerInNetwork()) { return true; } } } return false; }