我目前在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!!!
}
向我們展示你的代碼! – 2014-09-26 12:59:57