当前位置: 首页>>代码示例>>C++>>正文


C++ QTcpSocket::disconnectFromHost方法代码示例

本文整理汇总了C++中QTcpSocket::disconnectFromHost方法的典型用法代码示例。如果您正苦于以下问题:C++ QTcpSocket::disconnectFromHost方法的具体用法?C++ QTcpSocket::disconnectFromHost怎么用?C++ QTcpSocket::disconnectFromHost使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在QTcpSocket的用法示例。


在下文中一共展示了QTcpSocket::disconnectFromHost方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。

示例1: readyRead

void TestHTTPServer::readyRead()
{
    QTcpSocket *socket = qobject_cast<QTcpSocket *>(sender());
    if (!socket || socket->state() == QTcpSocket::ClosingState)
        return;

    if (!m_directories.isEmpty()) {
        serveGET(socket, socket->readAll());
        return;
    }

    if (m_state == Failed || (m_waitData.body.isEmpty() && m_waitData.headers.count() == 0)) {
        qWarning() << "TestHTTPServer: Unexpected data" << socket->readAll();
        return;
    }

    if (m_state == AwaitingHeader) {
        QByteArray line;
        while (!(line = socket->readLine()).isEmpty()) {
            line.replace('\r', "");
            if (line.at(0) == '\n') {
                m_state = AwaitingData;
                m_data += socket->readAll();
                break;
            } else {
                if (!m_waitData.headers.contains(line)) {
                    qWarning() << "TestHTTPServer: Unexpected header:" << line
                               << "\nExpected headers: " << m_waitData.headers;
                    m_state = Failed;
                    socket->disconnectFromHost();
                    return;
                }
            }
        }
    }  else {
        m_data += socket->readAll();
    }

    if (!m_data.isEmpty() || m_waitData.body.isEmpty()) {
        if (m_waitData.body != m_data) {
            qWarning() << "TestHTTPServer: Unexpected data" << m_data << "\nExpected: " << m_waitData.body;
            m_state = Failed;
        } else {
            socket->write(m_replyData);
        }
        socket->disconnectFromHost();
    }
}
开发者ID:2gis,项目名称:2gisqt5android,代码行数:48,代码来源:testhttpserver.cpp

示例2: slotNewConnectionHandler

void MyHttpServer::slotNewConnectionHandler()
{
    qDebug() << " [ ]Have a new connection!";
    QTcpSocket* sock = m_pServer.nextPendingConnection();
    sock->waitForReadyRead();
    QByteArray request(sock->readAll());
    qDebug() << request;
    QStringList buf = QString(request).split(' ');

    if(buf.at(0) == "GET")
    {
        QString responce = "HTTP/1.1 200 OK\r\n\r\n%1";
        sock->write(responce.arg(QTime::currentTime().toString()).toLatin1());
        sock->waitForBytesWritten();
        sock->disconnectFromHost();
        sock->deleteLater();
        return;
    }

    if(buf.at(0) == "POST")
    {
	QString destUrl(buf.at(1));
        sock->waitForReadyRead();
        QByteArray data(sock->readAll());
        qDebug() << "put " << QString(data) << " into " << destUrl;
        QString responce = "HTTP/1.1 200 OK\r\n\r\n";
        sock->write(responce.toLatin1());
        sock->waitForBytesWritten();
        sock->disconnectFromHost();
        sock->deleteLater();

        //QByteArray payload;
        //payload.append(QString(data).split('=').at(1));
        //payload = QByteArray::fromBase64(QByteArray::fromPercentEncoding(payload));
        //qDebug() << payload;

        //QJsonDocument doc = QJsonDocument::fromJson(payload);
        //QJsonObject jObj = doc.object();
        //QString table = destUrl.split('/').at(2);
        //qDebug() << "table: " << table << " object: " << jObj;


        return;
    }

//    connect(sock, SIGNAL(readyRead()), this, SLOT(slotReadDataHandler()));
//    connect(sock, SIGNAL(disconnected()), this, SLOT(slotDisconnectedHandler()));
}
开发者ID:mariarti91,项目名称:testRest,代码行数:48,代码来源:MyHttpServer.cpp

示例3: processDeviceCommandSocket

void ServerCore::processDeviceCommandSocket()
{
	if (!serverStart)
	{
		return;
	}

	QTcpSocket *socket = deviceCmdServer->nextPendingConnection();

	QObject::connect(socket, &QTcpSocket::readyRead, [=]
	{
		QByteArray byteArray = socket->readAll();
		QJsonDocument jsonDoc = QJsonDocument::fromJson(byteArray);
		QJsonObject jsonObj = jsonDoc.object();

		QVariantMap retParamMap = prepareDataForDevice(jsonObj);
		TCP_REPLY_TYPE retType = (TCP_REPLY_TYPE)retParamMap[JSON_KEY_RETURN_TYPE].toInt();

		QString retString = JsonGenerator::GenerateJsonReply(retType, retParamMap);
		QString peerAddress = socket->peerAddress().toString();
		socket->write(retString.toLatin1());

		bool isSuccess = socket->waitForBytesWritten();

		Q_EMIT dataWrittenToDevice(peerAddress, retString);

		socket->disconnectFromHost();
	});

	QObject::connect(socket, &QTcpSocket::disconnected, [=]
	{
		socket->deleteLater();
	});
}
开发者ID:cyril0108,项目名称:samidevice,代码行数:34,代码来源:servercore.cpp

示例4: kDebug

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)) );
    }
}
开发者ID:mcanes,项目名称:kdevelop-python,代码行数:33,代码来源:navigationwidget.cpp

示例5: sendCommandToDevice

void ServerCore::sendCommandToDevice(QString deviceUID, QVariantMap paramMap)
{
	QTcpSocket *socket = createSocket(deviceUID);

	QObject::connect(socket, &QTcpSocket::readyRead, [=]
	{
		QByteArray byteArray = socket->readAll();
		QJsonDocument jsonDoc = QJsonDocument::fromJson(byteArray);
		QJsonObject jsonObj = jsonDoc.object();

		if (jsonObj[JSON_KEY_STATUS].toInt() == STATUS_SUCCESSFUL)
		{
			QVariantMap retMap = jsonObj.toVariantMap();
			Q_EMIT commandReturned(deviceUID, retMap);
		}

		socket->disconnectFromHost();
	});

	QObject::connect(socket, &QTcpSocket::disconnected, [=]
	{
		socket->deleteLater();
	});

	QString jsonCmd = JsonGenerator::GenerateJsonCommand(TCP_COMMAND_TYPE::SEND_COMMAND_TO_DEVICE, paramMap);

	socket->write(jsonCmd.toLatin1());

	socket->waitForBytesWritten();
	socket->waitForReadyRead();
}
开发者ID:cyril0108,项目名称:samidevice,代码行数:31,代码来源:servercore.cpp

示例6: queryDeviceDisplayInfo

void ServerCore::queryDeviceDisplayInfo(QString deviceUID)
{
	QTcpSocket *socket = createSocket(deviceUID);

	QObject::connect(socket, &QTcpSocket::readyRead, [=]
	{
		QByteArray byteArray = socket->readAll();
		QJsonDocument jsonDoc = QJsonDocument::fromJson(byteArray);
		QJsonObject jsonObj = jsonDoc.object();

		if (jsonObj[JSON_KEY_STATUS].toInt() == STATUS_SUCCESSFUL)
		{
			QVariantMap retMap = jsonObj.toVariantMap();
			Q_EMIT displayInfoRecieved(deviceUID, retMap);
		}

		socket->disconnectFromHost();
	});

	QObject::connect(socket, &QTcpSocket::disconnected, [=]
	{
		socket->deleteLater();
	});

	QVariantMap paramMap;
	paramMap.insert(JSON_KEY_SEQ, 1234);

	QString jsonCmd = JsonGenerator::GenerateJsonCommand(TCP_COMMAND_TYPE::QUERY_DEVICE_DISPLAY_INFO, paramMap);

	socket->write(jsonCmd.toLatin1());
}
开发者ID:cyril0108,项目名称:samidevice,代码行数:31,代码来源:servercore.cpp

示例7: run

void SendThread::run()
{
QTcpSocket client;
qDebug() << "Thread Descriptor :" << socketDescriptor;
if (!client.setSocketDescriptor(socketDescriptor))
{
qDebug() << client.error();
return;
}
qDebug() << "Thread : Connected";

//send File
QFile inputFile(FILENAME);
QByteArray read;
inputFile.open(QIODevice::ReadOnly);
while(1)
{
read.clear();
read = inputFile.read(32768*8);
qDebug() << "Read : " << read.size();
if(read.size()==0)
break;

qDebug() << "Written : " << client.write(read);
client.waitForBytesWritten();
read.clear();
}
inputFile.close();
client.disconnectFromHost();
client.waitForDisconnected();
qDebug() << "Thread : File transfer completed";
}
开发者ID:hhvvkk,项目名称:COS301DistrobutedApplicationManger,代码行数:32,代码来源:sendthread.cpp

示例8: sendResponse

void Server::sendResponse() {
    QTcpSocket *clientConnection = tcpServer->nextPendingConnection();
    connect(clientConnection, SIGNAL(disconnected()), clientConnection, SLOT(deleteLater()));

    stringstream peerStream;
    peerStream << clientConnection->peerAddress().toString().toStdString()
            << ":"
            << clientConnection->peerPort();
    string peer = peerStream.str();

    if (clientConnection->waitForReadyRead(10000)) {
        clientConnection->readLine(readBuffer, BUFFER_LEN);
        string message(readBuffer);
        string deviceId = "";

        if (message.length() > 4) {
            deviceId = message.substr(4);
        }

        if (message.find("GET ", 0, 4) == 0) {
            string response = processGetOpertion(peer, deviceId);
            clientConnection->write(response.c_str());
        } else if (message.find("ADD ", 0, 4) == 0) {
            bool added = processAddOpertion(deviceId);
            if (added) {
                clientConnection->write("ADDED");
            } else {
                clientConnection->write("NOT ADDED");
            }
        }
    }
    clientConnection->disconnectFromHost();
}
开发者ID:ocmwdt,项目名称:usbwatcher,代码行数:33,代码来源:Server.cpp

示例9: run

void ClientThread::run()
{
    QTcpSocket tcpSocket;
    if (!tcpSocket.setSocketDescriptor(m_socketDescriptor)) {
        qWarning() << ":(((";
        emit error(tcpSocket.error());
        return;
    }

    m_running = true;

    QString command, response;

    // Send greetings
    tcpSocket.write("OK MPD 0.12.2\n");

    while (m_running && (tcpSocket.state() == QAbstractSocket::ConnectedState)) {
        m_running = tcpSocket.waitForReadyRead();   // Wait for command, 
                                                    // if none is received until timeout
                                                    // (default 30 seconds, stop running).

        command = QString(tcpSocket.readLine()).trimmed();
       
        qDebug() << command;

        tcpSocket.write(parseCommand(command).toLocal8Bit());
    }

    tcpSocket.disconnectFromHost();
}
开发者ID:sandsmark,项目名称:impd,代码行数:30,代码来源:clientthread.cpp

示例10: slt_ConnectionHandler

void HTTPServer::slt_ConnectionHandler()
{
    qDebug() << "[HTTPServer:]\tHave a new connection\n";
    QTcpSocket * socket = server.nextPendingConnection();
    socket->waitForReadyRead();
    QByteArray request(socket->readAll());
    QStringList buf = QString(request).split(' ');

    qDebug() << "Data received:\t" << buf.at(0);

    if(buf.at(0) == "POST")
    {
        QString responce = "HTTP/1.1 200 OK\r\n\r\n%1";
        socket->waitForReadyRead();
        QByteArray data(socket->readAll());
        socket->write(responce.toLatin1());
        socket->waitForBytesWritten();
        socket->disconnectFromHost();
        socket->deleteLater();

        qDebug() << "Data received: " << data;
        //--------
        //QJsonDocument doc = QJsonDocument::fromJson(data);
        //parse(doc);
    }
}
开发者ID:Aspenka,项目名称:SSD,代码行数:26,代码来源:HTTPServer.cpp

示例11: run

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();

}
开发者ID:Sassinak,项目名称:cll12-Pong,代码行数:29,代码来源:threadjoueurs.cpp

示例12: newRISRequest

void ListenRISRequests::newRISRequest()
{
    QTcpSocket *tcpSocket = m_tcpRISServer->nextPendingConnection();
    QString risRequestData;

    INFO_LOG("Rebuda peticio de la IP " + tcpSocket->peerAddress().toString());
    if (tcpSocket->waitForReadyRead(TimeOutToReadData))
    {
        risRequestData = QString(tcpSocket->readAll());
        INFO_LOG("Dades rebudes: " + risRequestData);
    }
    else
    {
        INFO_LOG("No s'ha rebut dades, error: " + tcpSocket->errorString());
    }

    INFO_LOG("Tanco socket");
    tcpSocket->disconnectFromHost();
    INFO_LOG("Faig delete del socket");
    delete tcpSocket;

    if (!risRequestData.isEmpty())
    {
        processRequest(risRequestData);
    }
}
开发者ID:151706061,项目名称:starviewer,代码行数:26,代码来源:listenrisrequests.cpp

示例13: recieveConnection

void Server::recieveConnection()
{
    QTcpSocket *clientConnection = tcpServer->nextPendingConnection();
    connect(clientConnection, SIGNAL(disconnected()), clientConnection, SLOT(deleteLater()));

    QString client_ip = clientConnection->peerAddress().toString();
    quint32 client_ip_int = clientConnection->peerAddress().toIPv4Address();

    emit write_message(tr("New connection from IP: %1").arg(client_ip));

    if (sockets->contains(client_ip_int)) {
        QTcpSocket *oldClientConnection = (QTcpSocket*) sockets->value(client_ip_int);
        if (oldClientConnection && oldClientConnection->state() != QAbstractSocket::UnconnectedState) {
            oldClientConnection->disconnectFromHost();
        }
        sockets->remove(client_ip_int);
    }

    sockets->insert(client_ip_int, clientConnection);

    connect(clientConnection, SIGNAL(stateChanged(QAbstractSocket::SocketState)), this, SLOT(socketStateChanged(QAbstractSocket::SocketState)));
    connect(clientConnection, SIGNAL(disconnected()), this, SLOT(clientDisconnected()));
    connect(clientConnection, SIGNAL(readyRead()), this, SLOT(recieveData()));
    connect(clientConnection, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(displayError(QAbstractSocket::SocketError)));
}
开发者ID:bukmare,项目名称:ESP_CStation,代码行数:25,代码来源:server.cpp

示例14: sizeof

void lc::ClientHelpNotificationServer::SendReply() {
    QByteArray block;
    QDataStream out{ &block, QIODevice::WriteOnly };
    out.setVersion( QDataStream::Qt_5_2 );
    out << ( quint16 )0;
    out << QString{ "Help demand retrieved." };
    out.device()->seek( 0 );
    out << ( quint16 )( block.size() - sizeof( quint16 ) );

    QTcpSocket *clientConnection = helpMessageServer->nextPendingConnection();
    QString peerAddress = clientConnection->peerAddress().toString();
    QString peerName;
    bool unknownClient = false;
    if ( settings->clIPsToClMap.contains( peerAddress ) ) {
        peerName = settings->clIPsToClMap[ peerAddress ]->name;
    } else {
        unknownClient = true;
    }

    connect( clientConnection, &QTcpSocket::disconnected, clientConnection, &QTcpSocket::deleteLater );
    clientConnection->write( block );
    clientConnection->disconnectFromHost();

    if ( unknownClient ) {
        QMessageBox requestReceivedBox{ QMessageBox::Information, tr( "Unknown client asked for help."),
                    tr( "An unknown client with IP '%1' asked for help.").arg( peerAddress ), QMessageBox::Ok };
        requestReceivedBox.exec();
    } else {
        QMessageBox requestReceivedBox{ QMessageBox::Information, tr( "'%1' asked for help.").arg( peerName ),
                    tr( "'%1' asked for help.").arg( peerName ), QMessageBox::Ok };
        requestReceivedBox.exec();
    }
}
开发者ID:markuspg,项目名称:Labcontrol,代码行数:33,代码来源:clienthelpnotificationserver.cpp

示例15: run

void QServerThread::run()
{
   QTcpSocket qsocket;
   if( qsocket.setSocketDescriptor( sd) == false)
   {
      AFERROR("QThreadServer::run: Can't set socket descriptor.\n");
      return;
   }

   af::Msg* msg = new af::Msg;
   if( afqt::recvMessage( &qsocket, msg))
   {
      if( recvMessage_handler_ptr == NULL )
      {
         emit newmsg( msg);
      }
      else
      {
         if( recvMessage_handler_ptr( &qsocket, msg) == false)
         {
            emit newmsg( msg);
         }
      }
   }
   qsocket.disconnectFromHost();
   if( qsocket.state() != QAbstractSocket::UnconnectedState ) qsocket.waitForDisconnected();
}
开发者ID:AlbertR,项目名称:cgru170,代码行数:27,代码来源:qserverthread.cpp


注:本文中的QTcpSocket::disconnectFromHost方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。