2014-09-26 66 views
-2

我目前在VS2010中實現了一個從TCP套接字讀取數據並填充數據庫的C++應用程序。 對於從TCP套接字讀取數據,我使用了QT readAll()函數。QTCPSocket的奇怪行爲readAll()函數

QByteArray text = socket.readAll();

我的應用程序不斷填充數據庫,所以我需要每5秒鐘讀取數據大約 然而,readAll()函數在第一次執行後(第一次沒有問題)沒有讀任何東西。文本的大小是0,而我期待它是75.

我檢查了套接字狀態,它已連接。 我也檢查錯誤,沒有什麼似乎是問題。 數據不斷從服務器傳輸(我用wireshark檢查過)

我該如何解決這種奇怪的行爲? 一件事,我懷疑是while循環,是的,但我想不出任何變通辦法

這裏是我的代碼:

#include "stdafx.h" 
#include "DataCollectionService.h" 

int main(int argv, char **args){ 

QCoreApplication app(argv, args);  

DataCollectionService *newCollection = new DataCollectionService(&app); 

QObject::connect(newCollection, SIGNAL(finished()), &app, SLOT(quit()));  

return(app.exec()); 
} 

/////////////////////////////////////////////// 
#pragma once 

#ifndef DATACOLLECTION_H 
#define DATACOLLECTION_H 

#include "TCPClient.h" 
#include "MySqlConnection.h" 
#include "QtGui\qapplication.h" 
#include "QtCore\qobject.h" 
#include "QtCore\qtimer.h" 

class DataCollectionService: public QObject{ 

Q_OBJECT 

public: 
DataCollectionService(QObject *parent = 0) : QObject(parent){ 

    newClient.InitializeTCPConnection(); 

    QTimer *timer = new QTimer(this); 
    connect(timer, SIGNAL(timeout()), this, SLOT(run())); 
    timer->start(1000); 
} 

private: 
MySqlConnection newConnection; 
TCPClient newClient;  

private slots: 
    void run(); 

signals: 
    void finished(); 

}; 
#endif 


//////////////////////////////////////////////////////////////////////////////// 
void DataCollectionService::run(){ 

newClient.UpdateMeasurements();       

} 

//////////////////////////////////////////////////////////////////////////////// 
void TCPClient::InitializeTCPConnection(){ 

socket.connectToHost("160.40.1.188", 2078, QIODevice::ReadWrite); ///remote host and port 

if(socket.waitForConnected()){ 

    if(!socket.waitForReadyRead()){ 
     transmissionError = true; 
    } 
} 

else{ 
    transmissionError = true; 
}  
} 


/////////////////////////////////////////////////////////////////////////////// 
void TCPClient::UpdateMeasurements(){ 

transmissionError = false; 

QByteArray text = socket.readAll(); ///////this gets data only once!!! 
} 
+0

向我們展示你的代碼! – 2014-09-26 12:59:57

回答

1

QT應用程序的設計與事件循環工作,其中發生在QApplication :: exec()。你不能只運行你的循環,你需要使用QT的機制。

+0

非常感謝你,我會嘗試,但我很肯定,這是問題 – roni 2014-09-26 13:15:09

+0

沒有運氣,即使我按照說明,我更新了問題的代碼,現在我正在使用qt機制。我仍然不能理解這種行爲。它只接收一次數據! – roni 2014-09-26 14:59:23

-1

終於解決了。

它需要添加

qApp-> processEvents();

的run()函數

一切工作的內部精細現在