bool ImapPrivate::connectToHost (const QString& host, quint16 port, bool useSsl) { #ifndef QT_NO_OPENSSL if (useSsl) socket = new QSslSocket; else socket = new QTcpSocket; #else Q_UNUSED(useSsl) socket = new QTcpSocket; #endif #ifndef QT_NO_OPENSSL if (useSsl) { QSslSocket *sslSocket = static_cast<QSslSocket *>(socket); sslSocket->connectToHostEncrypted(host, port); return(sslSocket->waitForEncrypted()); } else { socket->connectToHost(host, port); return(socket->waitForConnected()); } #else socket->connectToHost(host, port); return(socket->waitForConnected()); #endif }
void ConnectTrd::connectOne(QString ip) { QTcpSocket *socket = new QTcpSocket(); connect(socket,SIGNAL(readyRead()),this,SLOT(canRead())); socket->connectToHost("192.168.1.240",AKHMI_PORT); socket->waitForConnected(); qDebug()<< socket->waitForConnected()<< socket->errorString(); }
//---------------------------------------------------------------------------------- void tst_QTcpServer::ipv4PerformanceTest() { QTcpSocket probeSocket; probeSocket.connectToHost(QtNetworkSettings::serverName(), 143); QVERIFY(probeSocket.waitForConnected(5000)); QTcpServer server; QVERIFY(server.listen(probeSocket.localAddress(), 0)); QTcpSocket clientA; clientA.connectToHost(server.serverAddress(), server.serverPort()); QVERIFY(clientA.waitForConnected(5000)); QVERIFY(server.waitForNewConnection(5000)); QTcpSocket *clientB = server.nextPendingConnection(); QVERIFY(clientB); QByteArray buffer(16384, '@'); QTime stopWatch; stopWatch.start(); qlonglong totalWritten = 0; while (stopWatch.elapsed() < 5000) { qlonglong writtenA = clientA.write(buffer.data(), buffer.size()); clientA.flush(); totalWritten += buffer.size(); while (clientB->waitForReadyRead(100)) { if (clientB->bytesAvailable() == writtenA) break; } clientB->read(buffer.data(), buffer.size()); qlonglong writtenB = clientB->write(buffer.data(), buffer.size()); clientB->flush(); totalWritten += buffer.size(); while (clientA.waitForReadyRead(100)) { if (clientA.bytesAvailable() == writtenB) break; } clientA.read(buffer.data(), buffer.size()); } qDebug("\t\t%s: %.1fMB/%.1fs: %.1fMB/s", probeSocket.localAddress().toString().toLatin1().constData(), totalWritten / (1024.0 * 1024.0), stopWatch.elapsed() / 1000.0, (totalWritten / (stopWatch.elapsed() / 1000.0)) / (1024 * 1024)); delete clientB; }
//----------------------------------------------------------------------------- void QGCCacheWorker::_testInternet() { /* To test if you have Internet connection, the code tests a connection to 8.8.8.8:53 (google DNS). It appears that some routers are now blocking TCP connections to port 53. So instead, we use a TCP connection to "github.com" (80). On exit, if the look up for “github.com” is under way, a call to abort the lookup is made. This abort call on Android has no effect, and the code blocks for a full minute. So to work around the issue, we continue a direct TCP connection to 8.8.8.8:53 on Android and do the lookup/connect on the other platforms. */ #if defined(__android__) QTcpSocket socket; socket.connectToHost("8.8.8.8", 53); if (socket.waitForConnected(2000)) { qCDebug(QGCTileCacheLog) << "Yes Internet Access"; emit internetStatus(true); return; } qWarning() << "No Internet Access"; emit internetStatus(false); #else if(!_hostLookupID) { _hostLookupID = QHostInfo::lookupHost("www.github.com", this, SLOT(_lookupReady(QHostInfo))); } #endif }
void ProtoConnect::connectToMaster(QString ipAddress, int serverPort, ProtocolHandler * protocolHandler){ QTcpSocket *socket = new QTcpSocket(this); //making sure it is disconnectedclose(); socket->connectToHost(ipAddress, serverPort); //wait for one second for connection if(!socket->waitForConnected(1000)){ //error qDebug()<<"Error when connecting"; return; } SocketClient *socketClient = new SocketClient(protocolHandler, socket); //connect(socket, SIGNAL(connected()), socketClient, SLOT(connected())); connect(socket, SIGNAL(readyRead()), socketClient, SLOT(readyRead())); connect(socket, SIGNAL(disconnected()), socketClient, SLOT(disconnected())); //write to the server to connect socket->write("||Hello AppMan||"); socket->flush(); //finally set the socket so that the network can use it protocolHandler->setSocket(socket); }
void FetchThread::process(QString phost) { QUdpSocket *udpSocket ; udpSocket= new QUdpSocket(0); udpSocket->bind(QHostAddress::LocalHost, 9999); udpSocket->waitForConnected(250); QTcpSocket socket; socket.connectToHost("localhost", 4949); socket.waitForConnected(500); while (socket.waitForReadyRead(250)); QString t_hello = socket.readAll(); qDebug() << "READ: " << t_hello; socket.write(QString("list\n").toStdString().c_str() ); while (socket.waitForReadyRead(250)); QString buf1 = socket.readAll(); qDebug() << "READ: " << buf1; QStringList list_probe = buf1.split(QRegExp("\\s+")); for (int z=0; z< list_probe.size(); z++) { QString probe=list_probe.at(z); QString cmd = QString("fetch ").append(probe).append("\n"); qDebug() << "cmd : " << cmd; socket.write(cmd.toStdString().c_str() ); while (socket.waitForReadyRead(250)); QString buf2 = socket.readAll(); qDebug() << "Rep fetch :" << buf2 << "\n"; QRegularExpression re("(\\w+).(\\w+) ([0-9.]+)\\n"); QRegularExpressionMatchIterator i = re.globalMatch(buf2); re.setPatternOptions(QRegularExpression::MultilineOption); while (i.hasNext()) { QRegularExpressionMatch match = i.next(); QString s_metric = match.captured(1); QString s_value = match.captured(3); QString s_mtr = "monit2influxdb,metric="+probe + "_" + s_metric + ",host=" + phost+ " value=" + s_value + " " + QString::number(1000000* QDateTime::currentMSecsSinceEpoch()); qDebug() << "metric: " << s_mtr.toLower(); udpSocket->writeDatagram(s_mtr.toStdString().c_str(), QHostAddress::LocalHost, 9999); } udpSocket->close(); } }
void ThreadJoueurs::run() { QTcpSocket unSocket; unSocket.setSocketDescriptor(m_socketDescriptor); if(unSocket.waitForConnected(1000)) { while(unSocket.ConnectedState) //.waitForReadyRead(1000)) { baRXInfos=unSocket.read(unSocket.bytesAvailable()); if(baRXInfos.left(1) == "&") //code de connection des joueurs { unSocket.write(baTXInfos.append(cNoJ)); //assignation du numero baTXInfos = TXInfosToJoueurs(m_tNouvellePartie,9); // trame de debut de partie (= NouvellePartie) } else { RXInfosFmJoueurs(baRXInfos); //recoit {'#', JnX, JnY} baTXInfos = TXInfosToJoueurs(m_txInfos,9); //repond trame {code, balle X, balle Y, J1X, J1Y, J2X, J2Y, ScoreA, ScoreB} } // code = '#' (normale), '$' (gagnant), '%' (Nouvelle Balle) unSocket.write(baTXInfos); unSocket.waitForBytesWritten(10); } } unSocket.disconnectFromHost(); unSocket.close(); }
NavigationWidget::NavigationWidget(KDevelop::DeclarationPointer declaration, KDevelop::TopDUContextPointer topContext, const QString& /* htmlPrefix */, const QString& /* htmlSuffix */) { kDebug() << "Navigation widget for Declaration requested"; m_topContext = topContext; initBrowser(400); DeclarationNavigationContext* context = new DeclarationNavigationContext(declaration, m_topContext); m_startContext = context; setContext(m_startContext); m_fullyQualifiedModuleIdentifier = context->m_fullyQualifiedModuleIdentifier; kDebug() << "Identifier: " << m_fullyQualifiedModuleIdentifier; if ( m_fullyQualifiedModuleIdentifier.length() ) { kDebug() << "Checking wether doc server is running"; QTcpSocket* sock = new QTcpSocket(); sock->connectToHost(QHostAddress::LocalHost, 1050, QTcpSocket::ReadOnly); bool running = sock->waitForConnected(300); if ( ! running ) { kDebug() << "Not running, starting pydoc server"; QProcess::startDetached("/usr/bin/env", QStringList() << "python" << QString(INSTALL_PATH) + "/pydoc.py" << "-p" << "1050"); usleep(100000); // give pydoc server 100ms to start up } else { sock->disconnectFromHost(); } delete sock; m_documentationWebView = new QWebView(this); m_documentationWebView->load(QUrl("http://localhost:1050/" + m_fullyQualifiedModuleIdentifier + ".html")); connect( m_documentationWebView, SIGNAL(loadFinished(bool)), SLOT(addDocumentationData(bool)) ); } }
void mjpegThread::run() { QTcpSocket *socket = new QTcpSocket(this); connect(socket, SIGNAL(connected()),this, SLOT(connected())); connect(socket, SIGNAL(disconnected()),this, SLOT(disconnected())); connect(socket, SIGNAL(readyRead()),this, SLOT(readyRead())); QUrl url(cfg->get("src1/url"), QUrl::TolerantMode); socket->connectToHost(url.host(), 80); if(!socket->waitForConnected(5000)) { qDebug() << "Error: " << socket->errorString(); } while (fRun) { sleep(1); } socket->close(); }
bool Server::SendData(QHostAddress ip_to, QString message) { bool result = false; QTcpSocket* tcpSocket = sockets->value(ip_to.toIPv4Address(), 0); if (tcpSocket && tcpSocket->state()==QAbstractSocket::ConnectedState && tcpSocket->isWritable()) { emit write_message(tr("Sending data (size=%1) to %2. Content: \"%3\"").arg(message.length()).arg(ip_to.toString()).arg(message)); tcpSocket->write(message.toUtf8()); result = tcpSocket->waitForBytesWritten(); } else { tcpSocket = new QTcpSocket(); tcpSocket->connectToHost(ip_to, remote_port, QIODevice::ReadWrite); tcpSocket->waitForConnected(5000); if (tcpSocket->state()==QAbstractSocket::ConnectedState) { emit write_message(tr("Sending data (size=%1) from new socket to %2. Content: \"%3\"").arg(message.length()).arg(ip_to.toString()).arg(message)); tcpSocket->write(message.toUtf8()); result = tcpSocket->waitForBytesWritten(5000); } else { emit error(tr("Client \"%1\" not found").arg(ip_to.toString())); } tcpSocket->abort(); delete tcpSocket; } return result; }
//---------------------------------------------------------------------------------- void tst_QTcpServer::ipv6Server() { #if defined(Q_OS_SYMBIAN) QSKIP("Symbian: IPv6 is not yet supported", SkipAll); #endif //### need to enter the event loop for the server to get the connection ?? ( windows) QTcpServer server; if (!server.listen(QHostAddress::LocalHostIPv6, 8944)) { QVERIFY(server.serverError() == QAbstractSocket::UnsupportedSocketOperationError); return; } QVERIFY(server.serverPort() == 8944); QVERIFY(server.serverAddress() == QHostAddress::LocalHostIPv6); QTcpSocket client; client.connectToHost("::1", 8944); QVERIFY(client.waitForConnected(5000)); QVERIFY(server.waitForNewConnection()); QVERIFY(server.hasPendingConnections()); QTcpSocket *serverSocket = 0; QVERIFY((serverSocket = server.nextPendingConnection())); }
void server::write(QString value) { QTcpSocket *client = Server->nextPendingConnection(); if (client->waitForConnected(3000)) { qDebug() << "Client Connected: ..."; client->write("The connection is sucessfull"); client->waitForBytesWritten(1000); client->waitForReadyRead(3000); qDebug() << "Reading" << client->bytesAvailable(); qDebug() << client->readAll(); client->close(); } else { qDebug() << "Connection Failed..."; } }
void NewGame::refreshGames() { this->ui->listRefresh->setEnabled(false); this->ui->listGame->clear(); unsigned int ip; unsigned int netmask = 0xffffff00; foreach (QNetworkInterface it, QNetworkInterface::allInterfaces()) foreach (QHostAddress addr, it.allAddresses()) if (addr.toIPv4Address() && 0xff000000 != 0x7f000000) ip = addr.toIPv4Address(); unsigned int networkaddr = ip & netmask; for (unsigned int i = 1; i < 256; i++) { unsigned int currentIp = networkaddr + i; QTcpSocket* s = new QTcpSocket(); s->connectToHost(QHostAddress(currentIp), 1338); static_cast<MainWindow*>(this->parent())->print_status("Scanning ...\tCurrent : " + QHostAddress(currentIp).toString()); if (s->waitForConnected(5)) { this->ui->listGame->addItem(new QListWidgetItem(QHostAddress(currentIp).toString())); QCoreApplication::processEvents(); // tell the slave this is just a search request s->write("s", 1); s->close(); } } static_cast<MainWindow*>(this->parent())->print_status("End of scan"); this->ui->listRefresh->setEnabled(true); }
void MT500::testConnection() { for(int i = 0; i < 6; i++) { if(!ipArray[i].ip.isEmpty()){ QString msg = "[" + QDateTime::currentDateTime().toString("MM/dd/yyyy hh:mm:ss") + "] "; QTcpSocket * test = new QTcpSocket; test->connectToHost(QHostAddress(ipArray[i].ip), ipArray[i].port); if(test->waitForConnected(2000)) { msg += ipArray[i].ip + ": Test Message Sent"; ui->testBrowser->append("<font color=green>" + msg + "</font>"); test->abort(); } else { msg += ipArray[i].ip + ": Failed to Connect"; ui->testBrowser->append("<font color=red>" + msg + "</font>"); } } } if(!initial) { QString fips = fipsNo.trimmed().remove("VAZ"); QString msgToSend = "A 100 " + QDateTime::currentDateTime().toString("MM/dd/yyyy hh:mm:ss") + " " + QString::number(boxGID); sendBase(msgToSend, true); sendRaw(msgToSend); sendRawStrtoIflows(QString(encode(msgToSend))); } else initial = false; }
int MainWindow::getSensorTemperature(){ // Get the server address and port from the settings dialog box int serverPort = this->dialog->getServerPort(); // get from the dialog box quint32 serverAddr = this->dialog->getIPAddress(); // from the dialog box QTcpSocket *tcpSocket = new QTcpSocket(this); // create socket tcpSocket->connectToHost(QHostAddress(serverAddr), serverPort); // connect if(!tcpSocket->waitForConnected(1000)){ //wait up to 1s for a connection statusBar()->showMessage("Failed to connect to server..."); return 1; } // Send the message "getTemperature" to the server tcpSocket->write("getTemperature"); if(!tcpSocket->waitForReadyRead(1000)){ // wait up to 1s for the server statusBar()->showMessage("Server did not respond..."); return 1; } // If the server has sent bytes back to the client if(tcpSocket->bytesAvailable()>0){ int size = tcpSocket->bytesAvailable(); // how many bytes are ready? char data[20]; // upper limit of 20 chars tcpSocket->read(&data[0],(qint64)size); // read the number of bytes rec. data[size]='\0'; // termintate the string this->curTemperature = atof(data); // string -> float conversion cout << "Received the data [" << this->curTemperature << "]" << endl; } else{ statusBar()->showMessage("No data available..."); } return 0; // the on_updateTemperature() slot will update the display }
bool Http::send(QString host, int port, QByteArray data, QByteArray &result, int timeout) { QByteArray response; QTcpSocket socket; int numRead = 0; int numReadTotal = 0; char buffer[50]; socket.connectToHost(QHostAddress(host),port); if (!socket.waitForConnected(timeout)) { return false; } socket.write(data); if (!socket.waitForBytesWritten(timeout)) { return false; } forever { numRead = socket.read(buffer, 50); numReadTotal += numRead; response.append(buffer,numRead); if (numRead == 0 && !socket.waitForReadyRead(timeout)) break; } socket.disconnectFromHost(); int header = response.indexOf("\r\n\r\n"); if (header != -1) { result = response.mid(header+4); } return true; }
//---------------------------------------------------------------------------------- void tst_QTcpServer::waitForConnectionTest() { QFETCH_GLOBAL(bool, setProxy); if (setProxy) { QFETCH_GLOBAL(int, proxyType); if (proxyType == QNetworkProxy::Socks5Proxy) { QSKIP("Localhost servers don't work well with SOCKS5", SkipAll); } } QTcpSocket findLocalIpSocket; findLocalIpSocket.connectToHost(QtNetworkSettings::serverName(), 143); QVERIFY(findLocalIpSocket.waitForConnected(5000)); QTcpServer server; bool timeout = false; QVERIFY(server.listen(findLocalIpSocket.localAddress())); QVERIFY(!server.waitForNewConnection(1000, &timeout)); QCOMPARE(server.serverError(), QAbstractSocket::SocketTimeoutError); QVERIFY(timeout); ThreadConnector connector(findLocalIpSocket.localAddress(), server.serverPort()); connector.start(); #if defined(Q_OS_WINCE) || defined(Q_OS_SYMBIAN) QVERIFY(server.waitForNewConnection(9000, &timeout)); #else QVERIFY(server.waitForNewConnection(3000, &timeout)); #endif QVERIFY(!timeout); }
//worker in thread void CommThrd::run() { QTcpSocket qtcpSelfClient; QHostAddress qhostLocal("127.0.0.1"); qtcpSelfClient.connectToHost(qhostLocal, 35791); //connect successfully if(qtcpSelfClient.waitForConnected()) { //send request message !!!need to be modified //replace \n to \r\n QRegExp qreTemp("\\n"); mpqstrRequ->replace(qreTemp, "\r\n"); QByteArray qbyaRequ = mpqstrRequ->toAscii(); int i=qtcpSelfClient.write(qbyaRequ); if(i==-1) return; //QMessageBox::information(this, "Composer Error", "Can't send request to localhost!"); qtcpSelfClient.waitForBytesWritten(); //read response int iAvail = 0; QByteArray qbyaResp; bool bReady = qtcpSelfClient.waitForReadyRead(30000); iAvail = qtcpSelfClient.bytesAvailable(); qbyaResp = qtcpSelfClient.read(iAvail); delete mpqstrRequ; mpqstrRequ = new QString(qbyaResp); //post message to UI ERespAvail *pclsEvnt = new ERespAvail() ; qApp->postEvent((QObject*)(pwdMainWin->pwinComposer), pclsEvnt); } //QMessageBox::information(this, "Composer Error", "Can't connect to localhost!"); }
void ServerSwitcher::run() { QString tmp ; QUrl url(this->mServer + this->mRequest) ; QTcpSocket sock ; sock.connectToHost(url.host(),url.port(80)); if( sock.waitForConnected() ) { tmp = "GET /nowgo/%1 HTTP/1.0\r\n" "Host: %2\r\n" "User-Agent: NullGet\r\n" "Connection: close\r\n" "\r\n"; tmp = tmp.arg(this->mRequest).arg(url.host()); sock.write(tmp.toLatin1()); if( sock.waitForBytesWritten() ) { QByteArray ball ; while( sock.waitForReadyRead() ) { if( ball.isEmpty()) ball = sock.readAll(); else ball += sock.readAll(); } qDebug()<< ball ; } } }
bool FilePrinter::detectCupsService() { QTcpSocket qsock; qsock.connectToHost("localhost", 631); bool rtn = qsock.waitForConnected() && qsock.isValid(); qsock.abort(); return rtn; }
void ServerCore::processNewDevice(QVariantMap& dataMap) { bool isSelfBroadcast = dataMap.contains(JSON_KEY_COMMAND) && dataMap[JSON_KEY_COMMAND] == CMD_QUERY && (!dataMap.contains(JSON_KEY_UID) || !dataMap.contains(JSON_KEY_DISPLAYNAME) || !dataMap.contains(JSON_KEY_IP)); if (isSelfBroadcast) { return; } QString deviceUID = dataMap[JSON_KEY_UID].toString(); QString deviceName = dataMap[JSON_KEY_DISPLAYNAME].toString(); QString deviceIP = dataMap[JSON_KEY_IP].toString(); QString deviceType = dataMap[JSON_KEY_TYPE].toString(); DeviceInfo devInfo(deviceUID, deviceName, deviceIP, deviceType); DeviceManagerModule()->AddDevice(deviceUID, devInfo); QVariantMap paramMap; paramMap.insert(JSON_KEY_SEQ, 1234); QTcpSocket *socket = new QTcpSocket(this); QObject::connect(socket, &QTcpSocket::readyRead, [=] { QByteArray byteArray = socket->readAll(); parseSupportCmds(deviceUID, byteArray); Q_EMIT deviceAdded(deviceUID); socket->disconnectFromHost(); }); QObject::connect(socket, static_cast<void(QAbstractSocket::*)(QAbstractSocket::SocketError)>(&QAbstractSocket::error), [=](QAbstractSocket::SocketError socketError) { qDebug() << "Socket Error" << socketError; }); QObject::connect(socket, &QTcpSocket::disconnected, [=] { socket->deleteLater(); }); socket->connectToHost(deviceIP, PORT_SERVER_BROADCAST, QIODevice::ReadWrite); socket->waitForConnected(); QString jsonCmd = JsonGenerator::GenerateJsonCommand(TCP_COMMAND_TYPE::QUERY_DEVICE_SUPPORT_CMDS, paramMap); socket->write(jsonCmd.toLatin1()); socket->flush(); socket->waitForBytesWritten(); socket->waitForReadyRead(); }
bool updatePrices::isInternetConnection() { QTcpSocket q; q.connectToHost("yahoo.com", 80, QIODevice::ReadOnly); while (q.waitForConnected(2000)) return true; return false; }
//--------------------utech--------------------utech--------------------utech-------------------- bool USalaryLocal::MySqlServerStart() { USalaryLocal::MySqlServerSetConfigFile(); QDir::setCurrent(QCoreApplication::applicationDirPath()+"/../mysql/bin"); QProcess::startDetached(USalaryLocal::MySqlServerProgramName()+" --standalone"); QTcpSocket socket; socket.connectToHost("localhost", USalaryLocal::MySqlPort()); return socket.waitForConnected(5000); }
QTcpSocket *KSocketFactory::synchronousConnectToHost(const QString &protocol, const QString &host, quint16 port, int msecs, QObject *parent) { QTcpSocket *socket = connectToHost(protocol, host, port, parent); if (!socket->waitForConnected(msecs)) setError(socket, QAbstractSocket::SocketTimeoutError, i18n("Timed out trying to connect to remote host")); return socket; }
//---------------------------------------------------------------------------------- void tst_QIODevice::constructing_QTcpSocket() { #if defined(Q_OS_WINCE) && defined(WINCE_EMULATOR_TEST) QSKIP("Networking tests in a WinCE emulator are unstable", SkipAll); #endif QTcpSocket socket; QIODevice *device = &socket; QVERIFY(!device->isOpen()); socket.connectToHost(QtNetworkSettings::serverName(), 143); QVERIFY(socket.waitForConnected(5000)); QVERIFY(device->isOpen()); while (!device->canReadLine()) QVERIFY(device->waitForReadyRead(5000)); char buf[1024]; memset(buf, 0, sizeof(buf)); qlonglong lineLength = device->readLine(buf, sizeof(buf)); QVERIFY(lineLength > 0); QCOMPARE(socket.pos(), qlonglong(0)); socket.close(); socket.connectToHost(QtNetworkSettings::serverName(), 143); QVERIFY(socket.waitForConnected(5000)); QVERIFY(device->isOpen()); while (!device->canReadLine()) QVERIFY(device->waitForReadyRead(5000)); char buf2[1024]; memset(buf2, 0, sizeof(buf2)); QCOMPARE(socket.readLine(buf2, sizeof(buf2)), lineLength); char *c1 = buf; char *c2 = buf2; while (*c1 && *c2) { QCOMPARE(*c1, *c2); ++c1; ++c2; } QCOMPARE(*c1, *c2); }
int main(int argc, char **argv) { QCoreApplication app(argc, argv); QStringList args = app.arguments(); QString appName = args.takeFirst(); bool notification = args.contains("-n"); if (notification) args.removeAll("-n"); if (args.size() < 2) { qDebug("usage: %s [-n] <service> <method> <arguments>", appName.toLocal8Bit().data()); return -1; } // try to process socket QIODevice *device = 0; QScopedPointer<QIODevice> devicePtr(device); QString service = args.takeFirst(); QUrl serviceUrl = QUrl::fromUserInput(service); QHostAddress serviceAddress(serviceUrl.host()); if (serviceAddress.isNull()) { QLocalSocket *localSocket = new QLocalSocket; device = localSocket; localSocket->connectToServer(service); if (!localSocket->waitForConnected(5000)) { qDebug("could not connect to service: %s", service.toLocal8Bit().data()); return -1; } } else { QTcpSocket *tcpSocket = new QTcpSocket; device = tcpSocket; int servicePort = serviceUrl.port() ? serviceUrl.port() : 5555; tcpSocket->connectToHost(serviceAddress, servicePort); if (!tcpSocket->waitForConnected(5000)) { qDebug("could not connect to host at %s:%d", serviceUrl.host().toLocal8Bit().data(), servicePort); return -1; } } QJsonRpcSocket socket(device); QString method = args.takeFirst(); QVariantList arguments; foreach (QString arg, args) arguments.append(arg); QJsonRpcMessage request = notification ? QJsonRpcMessage::createNotification(method, arguments) : QJsonRpcMessage::createRequest(method, arguments); QJsonRpcMessage response = socket.sendMessageBlocking(request, 5000); if (response.type() == QJsonRpcMessage::Error) { qDebug("error(%d): %s", response.errorCode(), response.errorMessage().toLocal8Bit().data()); return -1; } qDebug() << response.result(); }
/* external interface called by meanwhileaccount */ void MeanwhileSession::connect(QString password) { HERE; int port, clientID, versionMajor, versionMinor; bool useCustomID; QString host; host = account->getServerName(); port = account->getServerPort(); useCustomID = account->getClientIDParams(&clientID, &versionMajor, &versionMinor); QTcpSocket *sock = new QTcpSocket(this); Kopete::SocketTimeoutWatcher* timeoutWatcher = Kopete::SocketTimeoutWatcher::watch(sock); if (timeoutWatcher) QObject::connect(timeoutWatcher, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(slotSocketAboutToClose())); sock->connectToHost(host, quint16(port)); // TODO - make asynchronous if (!sock->waitForConnected()) { KMessageBox::queuedMessageBox(0, KMessageBox::Error, i18n( "Could not connect to server"), i18n("Meanwhile Plugin"), KMessageBox::Notify); delete sock; return; } socket = sock; /* we want to receive signals when there is data to read */ QObject::connect(sock, SIGNAL(readyRead()), this, SLOT(slotSocketDataAvailable())); QObject::connect(sock, SIGNAL(aboutToClose()), this, SLOT(slotSocketAboutToClose())); /* set login details */ mwSession_setProperty(session, mwSession_AUTH_USER_ID, g_strdup(account->meanwhileId().toAscii()), g_free); mwSession_setProperty(session, mwSession_AUTH_PASSWORD, g_strdup(password.toAscii()), g_free); /* set client type parameters */ if (useCustomID) { mwSession_setProperty(session, mwSession_CLIENT_TYPE_ID, GUINT_TO_POINTER(clientID), NULL); mwSession_setProperty(session, mwSession_CLIENT_VER_MAJOR, GUINT_TO_POINTER(versionMajor), NULL); mwSession_setProperty(session, mwSession_CLIENT_VER_MINOR, GUINT_TO_POINTER(versionMinor), NULL); } /* go!! */ mwSession_start(session); }
void MessageWidget::connectToClient() { QTcpSocket *socket = new QTcpSocket(); socket->connectToHost(this->clientIP,4444,QTcpSocket::ReadWrite); if (!socket->waitForConnected(2000)) { QMessageBox::warning(this,"Connection problem:", "Connection to client failed!", QMessageBox::Close); } delete socket; }
/** Attempts a connection to <b>host</b> on <b>port</b>. Returns true if the * connection was successful, or false if the connection attempt failed. */ bool net_test_connect(QHostAddress host, quint16 port, int timeout) { QTcpSocket sock; sock.connectToHost(host, port); if (!sock.waitForConnected(timeout)) { return false; } sock.disconnectFromHost(); return true; }
void QDesignerServer::sendOpenRequest(int port, const QStringList &files) { QTcpSocket *sSocket = new QTcpSocket(); sSocket->connectToHost(QHostAddress::LocalHost, port); if(sSocket->waitForConnected(3000)) { foreach(const QString &file, files) { QFileInfo fi(file); sSocket->write(fi.absoluteFilePath().toUtf8() + '\n'); }