ich arbeite gerade an einer kleinen Qt-App für Android, wo Daten über W-LAN von einem anderen Gerät empfangen werden sollen. Diese Daten werden dann zyklich (alle 50ms) von einem Programmteil "abgeholt". Hierfür habe ich eine Socket-Klasse geschrieben:
Code: Alles auswählen
TCPSocket::TCPSocket(QObject *parent) :
QObject(parent)
{
reconnectTimer = new QTimer(this);
m_tcpSocket = new QTcpSocket(this);
connect(this, SIGNAL(startTimer()), this, SLOT(startTimerSlot()));
connect(this, SIGNAL(stopTimer()), this, SLOT(stopTimerSlot()));
connect(reconnectTimer, SIGNAL(timeout()), this, SLOT(reconnectTimerSlot()));
reconnectTimer->setInterval(5000);
connectServer();
}
void TCPSocket::connectServer()
{
if (!reconnectTimer->isActive())
{
emit startTimer();
}
m_tcpSocket->abort();
m_tcpSocket->connectToHost(IP, PORT);
connect(m_tcpSocket, SIGNAL(readyRead()), this, SLOT(readMesg()));
connect(m_tcpSocket, SIGNAL(disconnected()), this, SLOT(onDisconnected()));
connect(m_tcpSocket, SIGNAL(connected()), this, SLOT(onConnected()));
}
Falls die Verbindung getrennt wird, wird so alle 5 Sekunden probiert, sie wieder herzustellen. Wenn das "connected"-Signal kommt, wird der Timer wieder ausgeschaltet:
Code: Alles auswählen
void TCPSocket::onConnected()
{
#ifdef DEBUG
qDebug() << QTime::currentTime().toString() << "TCPSocket: Connected... ";
#endif
bIsConnected = true;
emit stopTimer();
}
Code: Alles auswählen
void TCPSocket::readMesg() //read msg
{
if(bIsConnected)
{
try
{
qDebug() << "Read: " << m_tcpSocket->bytesAvailable();
QByteArray qba = m_tcpSocket->readAll();
for (int i=0; i<qba.length(); i++)
{
queue.enqueue(qba[i]);
}
}
catch (std::exception &e)
{
qDebug() << "Exception: " << e.what();
}
}
}
Code: Alles auswählen
int TCPSocket::receiveData( U_BYTE_8 *receivedData )
{
int i=0;
qDebug() << queue.size();
while (!queue.isEmpty())
{
receivedData[i] = queue.dequeue();
i++;
}
qDebug() << "finished.";
return i;
}
Code: Alles auswählen
qDebug() << "Read: " << m_tcpSocket->bytesAvailable();
Code: Alles auswählen
QByteArray qba = m_tcpSocket->readAll();
Code: Alles auswählen
m_tcpSocket->write(buffer);
Habt Ihr da einen Tip für mich? Muss ich das noch irgendwie mit Semaphoren schützen? Oder weitere Abfragen machen??? Bin da langsam echt ratlos...
Vielen Dank im Voraus,
Ozzy