本文整理汇总了C++中QTcpSocket::waitForDisconnected方法的典型用法代码示例。如果您正苦于以下问题:C++ QTcpSocket::waitForDisconnected方法的具体用法?C++ QTcpSocket::waitForDisconnected怎么用?C++ QTcpSocket::waitForDisconnected使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类QTcpSocket
的用法示例。
在下文中一共展示了QTcpSocket::waitForDisconnected方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: 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";
}
示例2: run
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();
}
示例3: 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();
}
示例4: AddNewClient
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();
}
}
示例5: incomingConnection
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();
}
}
}
示例6: onNewConnection
void CmdServer::onNewConnection()
{
QTcpSocket *sk = listenner_.nextPendingConnection();
sk->waitForDisconnected(50);
QString cmd = sk->readAll();
QString handlerStr = cmd.section(" ", 0, 0);
QObject *handlerObj = handlers_[handlerStr];
if (handlerObj)
QMetaObject::invokeMethod(handlerObj, "commandReceived", Q_ARG(QString, cmd.section(" ", 1)));
}
示例7: run
void TCPThread::run() {
QTcpSocket tcpSocket;
if (!tcpSocket.setSocketDescriptor(socketDescriptor_)) {
emit error(tcpSocket.error());
return;
}
qint64 x = 0;
while(x < data.size()){
qint64 y= tcpSocket.write(data);
x+= y;
qDebug()<< x << " to: " << socketDescriptor_;
}
tcpSocket.disconnectFromHost();
tcpSocket.waitForDisconnected();
}
示例8: run
void UekiAccessServerThread::run()
{
QTcpSocket tcpSocket;
if (!tcpSocket.setSocketDescriptor(socketDescriptor)) {
emit error(tcpSocket.error());
return;
}
QByteArray block;
QDataStream out(&block, QIODevice::WriteOnly);
out.setVersion(QDataStream::Qt_4_0);
out << (quint16)0;
out.device()->seek(0);
out << (quint16)(block.size() - sizeof(quint16));
tcpSocket.write(block);
tcpSocket.disconnectFromHost();
tcpSocket.waitForDisconnected();
}
示例9: run
//! [1]
void FortuneThread::run()
{
QTcpSocket tcpSocket;
//! [1] //! [2]
if (!tcpSocket.setSocketDescriptor(socketDescriptor)) {
emit error(tcpSocket.error());
return;
}
//! [2] //! [3]
QByteArray block;
QDataStream out(&block, QIODevice::WriteOnly);
out.setVersion(QDataStream::Qt_4_0);
out << text;
//! [3] //! [4]
tcpSocket.write(block);
tcpSocket.disconnectFromHost();
tcpSocket.waitForDisconnected();
}
示例10: LOGL
void
ITunesScript::transmit( const QString& data )
{
// thread-safe, basically
int const port = m_listener->GetPort();
LOGL( 3, "ITunesScript data being sent " << data << " to port " << port );
QTcpSocket socket;
socket.connectToHost( QHostAddress::LocalHost, port );
if ( socket.waitForConnected( 1000 ) ) //FIXME hangs GUI thread?
{
int bytesWritten = socket.write( data.toUtf8() );
socket.flush();
socket.waitForDisconnected( 1000 ); //FIXME hangs?
if ( bytesWritten == -1 )
{
LOGL( 1, "Sending submission through socket failed." )
}
}
示例11: executeClient
void QxTransaction::executeClient(IxService * pService, const QString & sMethod)
{
if ((pService == NULL) || sMethod.isEmpty()) { qAssert(false); return; }
if (pService->getServiceName().isEmpty()) { pService->setMessageReturn(qx_bool(QX_ERROR_SERVICE_NOT_SPECIFIED, "[QxOrm] empty service name")); return; }
pService->registerClass();
QTcpSocket socket;
QString serverName = QxConnect::getSingleton()->getIp();
long serverPort = QxConnect::getSingleton()->getPort();
socket.connectToHost(serverName, serverPort);
if (! socket.waitForConnected(QxConnect::getSingleton()->getMaxWait()))
{ pService->setMessageReturn(qx_bool(QX_ERROR_SERVER_NOT_FOUND, "[QxOrm] unable to connect to server")); return; }
if (m_sTransactionId.isEmpty())
{ setTransactionId(QUuid::createUuid().toString()); }
setIpSource(socket.localAddress().toString());
setPortSource(socket.localPort());
setIpTarget(serverName);
setPortTarget(serverPort);
setServiceName(pService->getServiceName());
setServiceMethod(sMethod);
setTransactionBegin(QDateTime::currentDateTime());
setInputParameter(pService->getInputParameter_BaseClass());
qx_bool bWriteOk = writeSocket(socket);
if (! bWriteOk) { pService->setMessageReturn(qx_bool(QX_ERROR_SERVICE_WRITE_ERROR, QString("[QxOrm] unable to write request to socket : '") + bWriteOk.getDesc() + QString("'"))); return; }
qx_bool bReadOk = readSocket(socket);
if (! bReadOk) { pService->setMessageReturn(qx_bool(QX_ERROR_SERVICE_READ_ERROR, QString("[QxOrm] unable to read reply from socket : '") + bReadOk.getDesc() + QString("'"))); return; }
pService->setOutputParameter(getOutputParameter());
pService->setMessageReturn(getMessageReturn());
setTransactionEnd(QDateTime::currentDateTime());
socket.disconnectFromHost();
if (socket.state() != QAbstractSocket::UnconnectedState)
{ socket.waitForDisconnected(QxConnect::getSingleton()->getMaxWait()); }
}
示例12: run
void QxThread::run()
{
m_bIsRunning = true;
while (m_bIsRunning)
{
while (m_iSocketDescriptor == 0) {
if (! m_bIsRunning) {
return;
}
msleep(5);
}
QTcpSocket socket;
doProcess(socket);
socket.disconnectFromHost();
if (socket.state() != QAbstractSocket::UnconnectedState)
{
socket.waitForDisconnected(QxConnect::getSingleton()->getMaxWait());
}
clearData();
if (m_pThreadPool) {
m_pThreadPool->setAvailable(this);
}
}
}
示例13: run
//.........这里部分代码省略.........
if (it.name()=="program")
{
program_id=it.value().toString();
token=token+"-"+program_id;
params<<program_id;
if (!params.at(0).isNull()||!params.at(0).isEmpty())
{
query.exec("INSERT INTO math.answer (an_user_id, an_token, an_complete, an_start_date, an_cp_id) VALUES (0, '"+token+"', 0, '"+dateTime.toString("yyyy-MM-dd hh:mm:ss")+"', '"+program_id+"');");
query.exec("SELECT @an_id:=LAST_INSERT_ID();");
query.next();
answerID = query.value(0).toString();
params<<answerID;
}
}
if (it.name()=="exec")
{
type=it.value().toString();
}
if (it.name()=="lang")
{
lang=it.value().toString();
params<<lang;
}
if (it.value().isObject())
{
if (type=="execute")
{
QScriptValueIterator sit(it.value());
while (sit.hasNext()) {
sit.next();
if (sit.value().isObject())//--- jeigu tai failas
{
QScriptValueIterator sits(sit.value());
while (sits.hasNext()) {
sits.next();
if (sits.value().toString()=="file")
{
sits.next();
query.exec("SELECT @pp_id:=pp_id FROM math.program_param_list,math.program_param WHERE ppl_pp_id=pp_id and ppl_cp_id="+program_id+" and pp_name='"+sits.name()+"'");
cout << program_id.toStdString() << " program id \n";
query.prepare("INSERT INTO math.answer_param_value (pv_value, pv_pp_id) VALUES (:val, @pp_id);");
query.bindValue(":val",sits.value().toString());
query.exec();
query.exec("SELECT @pv_id:=LAST_INSERT_ID();");
query.exec("INSERT INTO math.answer_param_list (anpl_an_id, anpl_pv_id) VALUES (@an_id, @pv_id)");
query.exec("SELECT BD_DATA FROM math.big_data where BD_ID="+sits.value().toString());
query.next();
file.setFileName(this->binaryPath+"/binaries/"+program_id+"/"+sits.value().toString());
params<<this->binaryPath+"/binaries/"+program_id+"/"+sits.value().toString();
if (file.open(QIODevice::WriteOnly | QIODevice::Text))
{
QTextStream out(&file);
out << query.value(0).toByteArray();
}
file.close();
}
}
}
else {
params<<sit.value().toString();
query.exec("SELECT @pp_id:=pp_id FROM math.program_param_list,math.program_param WHERE ppl_pp_id=pp_id and ppl_cp_id="+program_id+" and pp_name='"+sit.name()+"'");
query.prepare("INSERT INTO math.answer_param_value (pv_value, pv_pp_id) VALUES (:val, @pp_id);");
query.bindValue(":val",sit.value().toString());
query.exec();
query.exec("SELECT @pv_id:=LAST_INSERT_ID();");
query.exec("INSERT INTO math.answer_param_list (anpl_an_id, anpl_pv_id) VALUES (@an_id, @pv_id)");
}
}
}
}
}
}
QSqlDatabase::removeDatabase(conName);
if (type=="execute")
{
if (params.at(0).isNull()||params.at(0).isEmpty())
{
socket.write("Nurodykite programa");
socket.waitForBytesWritten();
}
else emit this->requestExecute(params);
}
if (type=="compile")
{
if (params.at(0).isNull()||params.at(0).isEmpty())
{
socket.write("Nurodykite programa");
socket.waitForBytesWritten();
}
else emit this->requestCompile(params);
}
// qDebug()<<QString(data);
socket.write(token.toLatin1());
socket.flush();
socket.waitForBytesWritten();
socket.waitForDisconnected();
socket.close();
}
示例14: run
//.........这里部分代码省略.........
Connection: close
Content-Type: text/html
construction de cette en-tête HTTP, il est nécessaire de la faire suivre par un saut de ligne
avant la partie html*/
QByteArray* NewByteArray = new QByteArray;
found = str.contains(".jpg", Qt::CaseInsensitive);
if (found==true)
{
*NewByteArray = "HTTP/1.1 200 OK\r\nConnection: close\r\nContent-Type: image/jpeg\r\n\n";
// creation d'un QbyteArray indiquant une image au format jpeg
}
found = str.contains(".html", Qt::CaseInsensitive);
if (found==true)
{
*NewByteArray = "HTTP/1.1 200 OK\r\nConnection: close\r\nContent-Type: text/html\r\n\n";
// creation d'un QbyteArray indiquant un texte au format html
}
found = str.contains(".pdf", Qt::CaseInsensitive);
if (found==true)
{
*NewByteArray = "HTTP/1.1 200 OK\r\nConnection: close\r\nContent-Type: application/pdf\r\n\n";
// creation d'un QbyteArray indiquant un texte au format html
}
found = str.contains(".mp3", Qt::CaseInsensitive);
if (found==true)
{
*NewByteArray = "HTTP/1.1 200 OK\r\nConnection: close\r\nContent-Type: audio/mp3\r\n\n";
// creation d'un QbyteArray indiquant un texte au format html
}
found = str.contains(".doc", Qt::CaseInsensitive) || str.contains(".docx", Qt::CaseInsensitive);
if (found==true)
{
*NewByteArray = "HTTP/1.1 200 OK\r\nConnection: close\r\nContent-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document\r\n\n";
}
found = str.contains(".pptx", Qt::CaseInsensitive);
if (found==true)
{
*NewByteArray = "HTTP/1.1 200 OK\r\nConnection: close\r\nContent-Type: application/vnd.ms-powerpoint\r\n\n";
}
*NewByteArray += file->readAll();
// temp a été redimensionné automatiquement
file->close();
MyHash->insert(str, NewByteArray);/*insère bytearray dans Hash*/
*MyHashSize+=NewByteArray->size();
MyHashKeys->append(str);
}
else
{
str =tr("erreur404");
}
}
else //requete deja dans le hash
MyHashKeys->append(MyHashKeys->takeAt(MyHashKeys->lastIndexOf(str))); //on met la key en derniere position de la liste (premiere pos = LRU)
temp = *MyHash->value(str);
}
if(str.contains("erreur404"))
statistiques->AddErreur404();
else
statistiques->AddTraitee();
statistiques->AddOctets(temp.size());
tcpSocket.write(temp);
//Gestion de la taille du cache, suppression du LRU (last recently used)
while(*MyHashSize > CACHE_SIZE && MyHash->count()>1 )//Tant qu'on ne dépasse pas la taille max et qu'il reste plus d'un item dans le Hash (on ne veut pas supprimer erreur 404)
{
*MyHashSize-=MyHash->value(MyHashKeys->first())->size();//On soustrait la taille du fichier qu'on va enlever
delete MyHash->value(MyHashKeys->first());
MyHash->remove(MyHashKeys->first());//On retire le LRU du cache
MyHashKeys->removeFirst();//on enlève la LRU key
}
// for(int i = 0;i<MyHashKeys->size();i++)
// cout<<MyHashKeys->value(i).toStdString()<<endl;
// cout<<*MyHashSize<<endl;
statistiques->SetCacheSize(*MyHashSize);
cout << "Finishing MySocketClient::run()" << endl;
//! [2] //! [3]
tcpSocket.disconnectFromHost();
tcpSocket.waitForDisconnected();
}
示例15: handleConnection
void SharedDaemon::handleConnection()
{
QTcpSocket *socket = nextPendingConnection();
if ( !socket ) return;
//the connecting socket should have sent password..
//the client should be sending a password..
socket->waitForReadyRead();
if (!socket->bytesAvailable())
{
//std::cout << "no bytes available to read" << std::endl;
socket->close();
return;
}
std::cout << "user: "
<< socket->peerAddress().toString().toStdString()
<< " is attempting to connect" << std::endl;
QAbstractSocket* finalSocket = NULL;
ConnectionType typeOfConnection = TcpConnection;
QByteArray result = socket->readAll();
QString input(result);
/// initial connection must pass password, but can optionally pass
/// whether the client canRender and what the threshold value should be..
JSONNode output;
/// check if this is a WebSocketConnection
QString response = "";
if(input.startsWith("{") && ParseInput(input,output))
{
finalSocket = socket;
typeOfConnection = TcpConnection;
} /// check if this is a WebSocketConnection..
else if(QWsSocket::initializeWebSocket(result,response))
{
/// this is a websocket connection, respond and get frame..
socket->write(response.toLatin1());
socket->flush();
QEventLoop loop;
matched_input = "";
QWsSocket* wssocket = new QWsSocket(socket);
connect(wssocket,SIGNAL(frameReceived(QString)),
this,SLOT(getPasswordMessage(QString)));
connect(wssocket,SIGNAL(frameReceived(QString)),
&loop,SLOT(quit()));
/// wait for password to be sent ..
/// std::cout << "waiting for password from websocket" << std::endl;
loop.exec();
disconnect(wssocket,SIGNAL(frameReceived(QString)),
this,SLOT(getPasswordMessage(QString)));
disconnect(wssocket,SIGNAL(frameReceived(QString)),
&loop,SLOT(quit()));
//std::cout << matched_input.toStdString() << std::endl;
if( !ParseInput(matched_input,output) )
{
//std::cout << "passwords do not match: "
// << matched_password.toStdString()
// << " " << password << std::endl;
wssocket->close("passwords do not match or operation timed out");
if(socket->state() != QAbstractSocket::UnconnectedState)
socket->waitForDisconnected();
wssocket->deleteLater();
return;
}
finalSocket = wssocket;
typeOfConnection = WSocketConnection;
} /// not sure what connection this is, reject it..
else
{
//send rejection notice..
std::string errorString = "Unknown connection..";
socket->write(errorString.c_str(),errorString.length());
socket->disconnectFromHost();
socket->waitForDisconnected();
return;
}
//passwords match enable RemoteProcess and get port remote Process is listening to.
//send host,port,security_key and whatever else so that remote machine can successfully reverse connect
std::string program = "remoteApp";
std::string clientName = "newclient1";
//.........这里部分代码省略.........