本文整理汇总了C++中QTcpSocket::waitForReadyRead方法的典型用法代码示例。如果您正苦于以下问题:C++ QTcpSocket::waitForReadyRead方法的具体用法?C++ QTcpSocket::waitForReadyRead怎么用?C++ QTcpSocket::waitForReadyRead使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类QTcpSocket
的用法示例。
在下文中一共展示了QTcpSocket::waitForReadyRead方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: clientServerLoop
//----------------------------------------------------------------------------------
void tst_QTcpServer::clientServerLoop()
{
QTcpServer server;
QSignalSpy spy(&server, SIGNAL(newConnection()));
QVERIFY(!server.isListening());
QVERIFY(!server.hasPendingConnections());
QVERIFY(server.listen(QHostAddress::Any, 11423));
QVERIFY(server.isListening());
QTcpSocket client;
QHostAddress serverAddress = QHostAddress::LocalHost;
if (!(server.serverAddress() == QHostAddress::Any))
serverAddress = server.serverAddress();
client.connectToHost(serverAddress, server.serverPort());
QVERIFY(client.waitForConnected(5000));
QVERIFY(server.waitForNewConnection(5000));
QVERIFY(server.hasPendingConnections());
QCOMPARE(spy.count(), 1);
QTcpSocket *serverSocket = server.nextPendingConnection();
QVERIFY(serverSocket != 0);
QVERIFY(serverSocket->write("Greetings, client!\n", 19) == 19);
serverSocket->flush();
QVERIFY(client.waitForReadyRead(5000));
QByteArray arr = client.readAll();
QCOMPARE(arr.constData(), "Greetings, client!\n");
QVERIFY(client.write("Well, hello to you!\n", 20) == 20);
client.flush();
QVERIFY(serverSocket->waitForReadyRead(5000));
arr = serverSocket->readAll();
QCOMPARE(arr.constData(), "Well, hello to you!\n");
}
示例2: newIncomingConnection
// Richiesta connessione TCP in ingresso
void DuktoProtocol::newIncomingConnection()
{
// Verifica presenza connessione pendente
if (!mTcpServer->hasPendingConnections()) return;
// Recupero connessione
QTcpSocket *s = mTcpServer->nextPendingConnection();
// Se sto già ricevendo o inviando, rifiuto la connessione
if (mIsReceiving || mIsSending)
{
s->close();
return;
}
// Aggiornamento interfaccia grafica
receiveFileStart();
// Impostazione socket TCP corrente
mCurrentSocket = s;
// Attesa header della connessione (timeout 10 sec)
if (!s->waitForReadyRead(10000))
{
// Non ho ricevuto l'header della connessione, chiudo
mCurrentSocket->close();
delete mCurrentSocket;
mCurrentSocket = NULL;
return;
}
// Registrazione gestori eventi socket
connect(mCurrentSocket, SIGNAL(readyRead()), this, SLOT(readNewData()), Qt::DirectConnection);
connect(mCurrentSocket, SIGNAL(disconnected()), this, SLOT(closedConnection()), Qt::QueuedConnection);
// Inizializzazione variabili
mIsReceiving = true;
mTotalReceivedData = 0;
mElementSize = -1;
mReceivedFiles = new QStringList();
mRootFolderName = "";
mRootFolderRenamed = "";
// -- Lettura header generale --
// Numero entità da ricevere
mCurrentSocket->read((char*) &mElementsToReceiveCount, sizeof(qint64));
// Dimensione totale
mCurrentSocket->read((char*) &mTotalSize, sizeof(qint64));
// Inizio lettura dati sui file
readNewData();
}
示例3: run
void ConnectionThread::run()
{
Debug() << "Thread started.";
QTcpSocket sock;
socketNoNagle(sockdescr);
if (!sock.setSocketDescriptor(sockdescr)) {
Error() << sock.errorString();
return;
}
QString remoteHostPort = sock.peerAddress().toString() + ":" + QString::number(sock.peerPort());
Log() << "Connection from peer " << remoteHostPort;
QString line;
forever {
if (sock.canReadLine() || sock.waitForReadyRead()) {
line = sock.readLine().trimmed();
while (StimApp::instance()->busy()) {
// special case case, stimapp is busy so keep polling with 1s intervals
Debug() << "StimApp busy, cannot process command right now.. trying again in 1 second";
sleep(1); // keep sleeping 1 second until the stimapp is no longer busy .. this keeps us from getting given commands while we are still initializing
}
// normal case case, stimapp not busy, proceed normally
QString resp;
resp = processLine(sock, line);
if (sock.state() != QAbstractSocket::ConnectedState) {
Debug() << "processLine() closed connection";
break;
}
if (!resp.isNull()) {
if (resp.length()) {
Debug() << "Sending: " << resp;
if (!resp.endsWith("\n")) resp += "\n";
QByteArray data(resp.toUtf8());
int len = sock.write(data);
if (len != data.length()) {
Debug() << "Sent " << len << " bytes but expected to send " << data.length() << " bytes!";
}
}
Debug() << "Sending: OK";
sock.write("OK\n");
} else {
Debug() << "Sending: ERROR";
sock.write("ERROR\n");
}
} else {
if (sock.error() != QAbstractSocket::SocketTimeoutError
|| sock.state() != QAbstractSocket::ConnectedState) {
Debug() << "Socket error: " << sock.error() << " Socket state: " << sock.state();
break;
}
}
}
Log() << "Connection ended (peer: " << remoteHostPort << ")";
Debug() << "Thread exiting.";
}
示例4: getMunin
void FetchThread::getMunin(t_metric pmetric)
{
QRegularExpression exp("^munin://([0-9a-zA-Z]+)/([0-9a-zA-Z_]+)/([0-9a-zA-Z.]+)$"); //munin://localhost/load/load.value
QRegularExpressionMatch match = exp.match(pmetric.source_url);
if (match.hasMatch() ){
qDebug() << "FT_getMunin: fetching " << match.captured(1) << "," << match.captured(2) << "," << match.captured(3) ;
QTcpSocket socket;
socket.connectToHost("localhost", 4949);
socket.waitForConnected(2000);
//qDebug() << "FT_getMunin: connected";
//socket.waitForBytesWritten(1000);
socket.waitForReadyRead(3000);
//qDebug() << socket.readAll();
//qDebug() << "FT_getMunin: request " << match.captured(2);
socket.write(QString("fetch ").append(match.captured(2)).append(QString("\n")).toStdString().c_str() );
while (socket.waitForReadyRead(600)){
QString r = socket.readAll();
//qDebug() << "FT_getMunin: Server response: " << r;
QRegularExpression exp2(match.captured(3).append(" ([0-9.]+)\\n"));
QRegularExpressionMatch match2 = exp2.match(r);
if (match2.hasMatch() ){
qDebug() << "FT_getMunin: Got answer : " << match2.captured(1);
pmetric.qq_item->setProperty("value",this->convert(pmetric, match2.captured(1)));
pmetric.qq_item->setProperty("text_value",match2.captured(1));
}
}
socket.close();
//qDebug() << "getMunin: Metric fetch done ";
} else qDebug() << "getMunin: Illegal metric url: " <<pmetric.source_url;
}
示例5: Receive
void SFEQuery::Receive(QTcpSocket &socket)
{
// QDataStream _in((QTcpSocket*)&socket);
_in.setVersion(QDataStream::Qt_4_7);
while(socket.bytesAvailable()<sizeof(quint32))
socket.waitForReadyRead(1000);
qDebug("reading %d",sizeof(quint32));
QByteArray ba = socket.read(sizeof(quint32));
_inblock.append(ba);
_in >> _size;
qDebug("cmd size: %d",_size);
quint32 left = _size- sizeof(quint32);
while(socket.bytesAvailable()<left){
qDebug("2 available: %d",(int)socket.bytesAvailable());
socket.waitForReadyRead(1000);
}
qDebug("reading: %d",left);
QByteArray ba2 = socket.read(left);
_inblock.append(ba2);
// _in.skipRawData(sizeof(quint32));
quint32 type;
_in >> type;
qDebug("got type: %d",type);
if (_type!=SFEQuery::NOTYPE_TYPE && type!=(quint32)_type)
qDebug("error type !=");
_type=(SFEQuery::QueryType)type;
doReceive();
}
示例6: sendToClient
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;
}
示例7: yearHasData
bool MainWindow::yearHasData(const int year){
QUrl url(compBase + "year_" + QString::number(year) + "month_04/day_01/");
QTcpSocket socket;
socket.connectToHost(url.host(), 80);
if (socket.waitForConnected()){
socket.write("HEAD" + url.path().toUtf8() + "HTTP/1.1\r\n" + "Host" + url.host().toUtf8() + "\r\n\r\n");
if (socket.waitForReadyRead()){
QByteArray bytes = socket.readAll();
if (bytes.contains("200 OK"))
return true;
}
}
return false;
}
示例8: createCustomConnection
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();
if(tcpSocket->state() != QAbstractSocket::UnconnectedState)
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);
}
}
示例9: run
void cTaskThd::run()
{
QTcpSocket sck;
while(1)
{
sck.close();
if(sck.setSocketDescriptor(getsocketDescriptor((cServer *)this->parent())))
if (sck.waitForReadyRead(SERVICE_TIMEOUT_SEC * 1000))
{
qDebug() << "线程" << this->id << " 将数据返回后将关闭连接" ;
sck.write(sck.readAll());
sck.waitForBytesWritten(3000);
}
}
}
示例10: receiveData
void receiveData()
{
QTcpSocket *clientConnection = tcpServer->nextPendingConnection();
clientConnection->waitForReadyRead();
QDataStream in(clientConnection);
in.setVersion(QDataStream::Qt_5_4);
QString text;
in>>text;
label->setText(text);
QString imageFn;
in>>imageFn;
if (QFile::exists(imageFn))
{
welcome->pictureLabel->setPixmap(QPixmap(imageFn).scaled(welcome->pictureLabel->size(), Qt::KeepAspectRatio));
}
}
示例11: run
/* FIXME: Qt manuals is saying this is the wrong way to create thread since version 4.x
we better use QThreadPool or similar but for now...
*/
void SlimIncomingHandler::run()
{
QString received;
QTcpSocket tcpSocket;
if (!tcpSocket.setSocketDescriptor(client))
{
qDebug() << "tcpSocket rip?";
emit error();
return ;
}
bExit = false;
tcpSocket.write("Slim -- V0.3\r\n");
while (!bExit) // todo mutex to make possible for server to force exit
{
if (tcpSocket.waitForReadyRead(FITNESSE_TIMEOUT))
{
received.append(QString(tcpSocket.readAll()));
qDebug() << received;
if (received.size() > 6)
{
SlimDeserializer dser(received);
dser.getLength();
CommandExecuter exe(dser.deserialize());
QString result = exe.executeAll();
qDebug() << "resultsend" << result.toUtf8();
tcpSocket.write(result.toUtf8());
// fixme failcheck
received ="";
}
// FIXME... parser
if (received.endsWith("bye")) // the later variant(\r\n) used when debugging since telnet adds \r\n
break;
}
else // timeout waitForDataTimeout
{
// tell client to die since there were no data from fitnesse server to process
qDebug() << "socket timeout";
bExit = true;
}
}
qDebug() << "die";
tcpSocket.close();
emit exited(this);
}
示例12: newIncomingConnection
// Richiesta connessione TCP in ingresso
void DuktoProtocol::newIncomingConnection()
{
// Recieve connection
QTcpSocket* s = mTcpServer->nextPendingConnection();
if(s == NULL) return;
// If we are already recieving or sending
// Pending header connection (timeout 10 sec)
if ((mIsReceiving | mIsSending) || !s->waitForReadyRead(10000))
{
s->close();
delete s;
return;
}
// Update GUI
receiveFileStart(s->peerAddress().toString());
// set current TCP socket
mCurrentSocket = s;
// Register socket's event handlers
connect(mCurrentSocket, SIGNAL(readyRead()), this, SLOT(readNewData()), Qt::DirectConnection);
connect(mCurrentSocket, SIGNAL(disconnected()), this, SLOT(closedConnectionTmp()), Qt::QueuedConnection);
// Initialize variables
mIsReceiving = true;
mTotalReceivedData = 0;
mElementSize = -1;
mReceivedFiles = new QStringList();
mRootFolderName.clear();
mRootFolderRenamed.clear();
mReceivingText = false;
mRecvStatus = FILENAME;
// -- Reading General header --
// Entities number to receive
mCurrentSocket->read((char*) &mElementsToReceiveCount, sizeof(qint64));
// total size
mCurrentSocket->read((char*) &mTotalSize, sizeof(qint64));
// Start reading data on file
readNewData();
}
示例13: readLine
QByteArray ImapPrivate::readLine (bool *ok) {
quint8 attempts = 0;
while (!socket->canReadLine() && attempts < 2) {
if (!socket->waitForReadyRead())
attempts++;
}
if (attempts >= 2) {
if (ok != NULL) *ok = false;
return(QByteArray());
}
if (ok != NULL) *ok = true;
#ifdef IMAP_DEBUG
QByteArray response = socket->readLine();
qDebug() << "readLine()" << response;
return(response);
#else
return(socket->readLine());
#endif
}
示例14: getSingleLongNick
QByteArray QQItemInfoHelper::getSingleLongNick(QString id)
{
QString single_long_nick_url = "/api/get_single_long_nick2?tuin=" + id+ "&vfwebqq=" + CaptchaInfo::instance()->vfwebqq() + "&t=" + QString::number(QDateTime::currentDateTime().toMSecsSinceEpoch());
Request req;
req.create(kGet, single_long_nick_url);
req.addHeaderItem("Host", "s.web2.qq.com");
req.addHeaderItem("Referer", "http://s.web2.qq.com/proxy.html?v=20110412001&callback=1&id=1");
req.addHeaderItem("Connection", "keep-live");
req.addHeaderItem("Content-Type","utf-8");
req.addHeaderItem("Cookie", CaptchaInfo::instance()->cookie());
QTcpSocket fd;
fd.connectToHost("s.web2.qq.com", 80);
fd.write(req.toByteArray());
fd.waitForReadyRead();
QByteArray result = fd.readAll();
fd.close();
return result;
}
示例15: readConnection
void CLCServer::readConnection()
{
QTcpSocket * sock = nextPendingConnection();
sock->waitForReadyRead();
QByteArray b = sock->readLine();
if(b.isEmpty()) return;
const char * cmd = b.data();
Arguments * a = parse_commandline(cmd);
QStringList l;
l << "CLCBrowser";
for(int i=1 ; i<a->argc ; ++i)
{
l << a->argv[i];
}
Arguments_destroy(a);
parseArgs(l, sock);
sock->close();
}