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(); } }
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())); }
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(); }); }
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(); }
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()); }
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"; }
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(); }
Connection* SharedDaemon::createCustomConnection(int listenSocketNum, void *data) { SharedDaemon::ConnectionType typeOfConnection = *((SharedDaemon::ConnectionType*)(data)); if(typeOfConnection == SharedDaemon::WSocketConnection ) { int descriptor = SingleThreadedAcceptSocket(listenSocketNum); QTcpSocket * tcpSocket = new QTcpSocket(); tcpSocket->setSocketDescriptor( descriptor, QAbstractSocket::ConnectedState ); tcpSocket->waitForReadyRead(); QString request = QString(tcpSocket->readAll()); if(request.size() == 0) /// firefox works differently, and sends 0 size messages { tcpSocket->close(); tcpSocket->disconnectFromHost(); tcpSocket->waitForDisconnected(); tcpSocket->deleteLater(); descriptor = SingleThreadedAcceptSocket(listenSocketNum); tcpSocket = new QTcpSocket(); tcpSocket->setSocketDescriptor( descriptor, QAbstractSocket::ConnectedState ); tcpSocket->waitForReadyRead(); request = QString(tcpSocket->readAll()); } return new WebSocketConnection(tcpSocket,request); } else { int descriptor = SingleThreadedAcceptSocket(listenSocketNum); return new SocketConnection(descriptor); } }
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(); }
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); } }
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 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); } }
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))); }
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(); } }
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(); }
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 lsLogServitemThreated::run() { QTcpSocket tcpSocket; if (!tcpSocket.setSocketDescriptor(socketDescriptor)) { emit error(tcpSocket.error()); return; } while ( tcpSocket.isOpen() ) { QByteArray block; QDataStream out(&block, QIODevice::WriteOnly); out.setVersion(QDataStream::Qt_4_0); out << (quint16)0; out << text; text.clear(); out.device()->seek(0); out << (quint16)(block.size() - sizeof(quint16)); tcpSocket.write(block); tcpSocket.flush(); while ( tcpSocket.isOpen() && text.isEmpty() ) { msleep(100); } } tcpSocket.disconnectFromHost(); tcpSocket.waitForDisconnected(); }
void SharedDaemon::AddNewClient(const std::string &host, const stringVector &args, void *cbdata) { /// Send appropriate message for TCP or WebConnection void** data = (void**)cbdata; ConnectionType typeOfConnection = *((ConnectionType*)(data[0])); QAbstractSocket* socket = static_cast<QAbstractSocket*>(data[1]); ViewerState* viewerState = static_cast<ViewerState*>(data[2]); JSONNode node; QString hostname = typeOfConnection == TcpConnection ? socket->localAddress().toString(): dynamic_cast<QWsSocket*>(socket)->internalSocket()->localAddress().toString(); if(hostMap.contains(hostname)) hostname = hostMap[hostname]; node["host"] = hostname.toStdString(); //host node["port"] = args[7]; //port node["version"] = args[2]; //version node["securityKey"] = args[9]; //key node["numStates"] = viewerState->GetNumStateObjects(); //number of states JSONNode::JSONArray rpc_array = JSONNode::JSONArray(); for(size_t i = 0; i < ViewerRPC::MaxRPC; ++i) { rpc_array.push_back(ViewerRPC::ViewerRPCType_ToString((ViewerRPC::ViewerRPCType)i)); } node["rpc_array"] = rpc_array; if(typeOfConnection == TcpConnection) { QTcpSocket *tsocket = dynamic_cast<QTcpSocket*>(socket); std::string message = node.ToString(); tsocket->write(message.c_str(),message.length()); if(tsocket->state() != QAbstractSocket::UnconnectedState) tsocket->waitForBytesWritten(); tsocket->disconnectFromHost(); if(tsocket->state() != QAbstractSocket::UnconnectedState) tsocket->waitForDisconnected(); //HKTODO: Do not delete connection (test fix for ORNL machines) //tsocket->deleteLater(); } else { QWsSocket *wsocket = dynamic_cast<QWsSocket*>(socket); wsocket->write(QString(node.ToString().c_str())); wsocket->flush(); if(wsocket->internalSocket()->state() != QAbstractSocket::UnconnectedState) wsocket->internalSocket()->waitForBytesWritten(); wsocket->close(""); wsocket->internalSocket()->disconnectFromHost(); if(wsocket->internalSocket()->state() != QAbstractSocket::UnconnectedState) wsocket->internalSocket()->waitForDisconnected(); wsocket->deleteLater(); } }
void Server::onConnect() { QTcpSocket *clientConnection = tcpServer->nextPendingConnection(); connect(clientConnection, SIGNAL(disconnected()), clientConnection, SLOT(deleteLater())); clientConnection->disconnectFromHost(); }
void Server::neueVerbindung() { QTcpSocket *neuerClient = server->nextPendingConnection(); if (anzahlClients >= CLIENTS_MAX) { neuerClient->disconnectFromHost(); } clients[anzahlClients++] = neuerClient; connect(neuerClient, SIGNAL(readyRead()), this, SLOT(nachrichtEmpfangen())); // sendeBegruessung(neuerClient); }
void CGProxy::newConnection() { QTcpSocket* newClient = m_LocalServer->nextPendingConnection(); if(m_LocalSocket) { newClient->disconnectFromHost(); return; } while( !m_LocalPackets.empty( ) ) { delete m_LocalPackets.front( ); m_LocalPackets.pop_front( ); } while( !m_RemotePackets.empty( ) ) { delete m_RemotePackets.front( ); m_RemotePackets.pop_front( ); } while( !m_PacketBuffer.empty( ) ) { delete m_PacketBuffer.front( ); m_PacketBuffer.pop_front( ); } newClient->setSocketOption(QAbstractSocket::LowDelayOption, 1); m_TotalPacketsReceivedFromLocal = 0; m_TotalPacketsReceivedFromRemote = 0; m_LastConnectionAttemptTime = 0; m_GameIsReliable = false; m_GameStarted = false; m_LeaveGameSent = false; m_ActionReceived = false; m_Synchronized = true; m_ReconnectPort = 0; m_PID = 255; m_ChatPID = 255; m_ReconnectKey = 0; m_NumEmptyActions = 0; m_NumEmptyActionsUsed = 0; m_LastAckTime = 0; m_LastActionTime = 0; m_LocalSocket = newClient; connect(m_LocalSocket, SIGNAL(disconnected()), this, SLOT(localDisconnected())); connect(m_LocalSocket, SIGNAL(disconnected()), m_LocalSocket, SLOT(deleteLater())); connect(m_LocalSocket, SIGNAL(readyRead()), this, SLOT(readLocalPackets())); }
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(); }
void ConnectionListener::incomingConnection(qintptr socketDescriptor) { if (m_accept) { emit log("Listener", "New connection: accepted."); m_accept = false; emit clientSuccessfullyConnected(); m_proxy.reset(new Proxy(m_mapData, m_pathMachine, m_prespammedPath, m_groupManager, m_mumeClock, m_mapCanvas, socketDescriptor, this)); if (getConfig().connection.proxyThreaded) { m_thread.reset(new QThread); m_proxy->moveToThread(m_thread.get()); // Proxy destruction stops the thread which then destroys itself on completion connect(m_proxy.get(), &QObject::destroyed, m_thread.get(), &QThread::quit); connect(m_thread.get(), &QThread::finished, m_thread.get(), &QObject::deleteLater); connect(m_thread.get(), &QObject::destroyed, this, [this]() { m_accept = true; m_proxy.release(); m_thread.release(); }); // Make sure if the thread is interrupted that we kill the proxy connect(m_thread.get(), &QThread::finished, m_proxy.get(), &QObject::deleteLater); // Start the proxy when the thread starts connect(m_thread.get(), &QThread::started, m_proxy.get(), &Proxy::start); m_thread->start(); } else { connect(m_proxy.get(), &QObject::destroyed, this, [this]() { m_accept = true; m_proxy.release(); }); m_proxy->start(); } } else { emit log("Listener", "New connection: rejected."); QTcpSocket tcpSocket; if (tcpSocket.setSocketDescriptor(socketDescriptor)) { QByteArray ba("\033[1;37;41mYou can't connect to MMapper more than once!\r\n" "Please close the existing connection.\033[0m\r\n"); tcpSocket.write(ba); tcpSocket.flush(); tcpSocket.disconnectFromHost(); tcpSocket.waitForDisconnected(); } } }
bool slm_machine::checkBuddyOnline(QString Buddy) { QTcpSocket *checkUser = new QTcpSocket(); checkUser->connectToHost(buddies->IPBuddyList[buddies->AliasBuddyList.indexOf(Buddy,0)], 3333,QIODevice::ReadOnly); if(checkUser->waitForConnected(500)) { checkUser->disconnectFromHost(); checkUser->close(); delete checkUser; return 1; } else { checkUser->disconnectFromHost(); checkUser->close(); delete checkUser; return 0; } }
/** * 接続を閉じる */ void YASWebProxy::closeProxySocket() { QTcpSocket* proxySocket = qobject_cast<QTcpSocket*>(sender()); if (proxySocket) { QTcpSocket* socket = qobject_cast<QTcpSocket*>(proxySocket->parent()); if (socket) socket->disconnectFromHost(); proxySocket->deleteLater(); } }
/** 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 WebProxy::closeConnection() { QTcpSocket *proxySocket = qobject_cast<QTcpSocket*>(sender()); if (proxySocket) { QTcpSocket *socket = qobject_cast<QTcpSocket*>(proxySocket->parent()); if (socket) socket->disconnectFromHost(); if (proxySocket->error() != QTcpSocket::RemoteHostClosedError) qWarning() << "Error for:" << proxySocket->property("url").toUrl() << proxySocket->errorString(); proxySocket->deleteLater();; } } //WebProxy::closeConnection
void TestHTTPServer::readyRead() { QTcpSocket *socket = qobject_cast<QTcpSocket *>(sender()); if (!socket || socket->state() == QTcpSocket::ClosingState) return; QByteArray ba = socket->readAll(); if (!dirs.isEmpty()) { serveGET(socket, ba); return; } if (m_hasFailed || waitData.isEmpty()) { qWarning() << "TestHTTPServer: Unexpected data" << ba; return; } for (int ii = 0; ii < ba.count(); ++ii) { const char c = ba.at(ii); if (c == '\r' && waitData.isEmpty()) continue; else if (!waitData.isEmpty() && c == waitData.at(0)) waitData = waitData.mid(1); else if (c == '\r') continue; else { QByteArray data = ba.mid(ii); qWarning() << "TestHTTPServer: Unexpected data" << data << "\nExpected: " << waitData; m_hasFailed = true; socket->disconnectFromHost(); return; } } if (waitData.isEmpty()) { socket->write(replyData); socket->disconnectFromHost(); } }
void MessageWidget::sendToClient(QString message) { QTcpSocket *socket = new QTcpSocket(); socket->connectToHost(this->clientIP,4444,QTcpSocket::ReadWrite); if (socket->waitForConnected(2000)) { socket->write(message.toLatin1()); socket->waitForReadyRead(300); socket->disconnectFromHost(); } else QMessageBox::warning(this,"Connection problem:", "Connection to client failed!", QMessageBox::Close); delete socket; }