QT NetworkManager initialazation and asynch problems - c++

Firstly, I'd like to trigger an initialization process whenever this class been created. (DNS lookups for known hosts, and and pre-handshake with hosts over a specified number of slots - this shall not be hardcoded once it has been tested) - while all the classes are being created, config is being read, etc.
Secondly, I'd like to allow parallelized request sending depending on the allowed (and opened) slots present for the specific host.
Quite frankly there's multiple issues with the following code;
Google seems to redirect, upon multiple requests at the same time to this host seems to result in a catastrophic failure, when x number or request triggers the finished signal, and that signals invokes my redirect checking and the first request get redirected, and I do seem to get the first reply back, with x error messages.
I cant seem to invoke deleteLater() from httpFinished for the same reason
I've could not find a way to wait for the slot number of request to be finished to start the next request in queue
The main goal would be to gather data from multiple APIs using a single network class, those requests would maybe occur the same time, may not.
Also there would be another request emitted just as POST, etc. - maybe 1 class / API?
Please note that the code is just test of concept and for testing purposes only, and this shall be cleaned after it has been fixed, this is not how I intended it to work at all.
nebula.pro
QT += core network
QT -= gui
TARGET = nebula
CONFIG += console
CONFIG -= app_bundle
TEMPLATE = app
SOURCES += main.cpp \
network.cpp
HEADERS += \
network.h
network.h
#ifndef NETWORK_H
#define NETWORK_H
#include <QObject>
#include <QtNetwork/QNetworkAccessManager>
#include <QtNetwork/QNetworkReply>
#include <QtNetwork/QHostInfo>
#include <QtNetwork/QSslConfiguration>
#include <QEventLoop>
class network : public QObject
{
Q_OBJECT
public:
explicit network(QObject *parent = 0);
~network();
void sendGet(const QUrl &url);
private:
QNetworkAccessManager networkAccessManager;
QHash<QString, QByteArray> usedSession;
QNetworkReply *reply;
QUrl url;
Q_INVOKABLE void init();
void replyFinished(QUrl &url, QNetworkReply *reply);
QList<QString> provideTcpHosts();
QList<QString> provideSslHosts();
QEventLoop eventLoop;
private slots:
void httpError();
void sslErrors(const QList<QSslError> &errors);
void httpFinished();
};
#endif // NETWORK_H
network.cpp
#include "network.h"
/**
* #brief network::network
* initialazing pre-networking initialization once the eventpool is ready
* #param parent
*/
network::network(QObject *parent) : QObject(parent)
{
QMetaObject::invokeMethod(this, "init", Qt::QueuedConnection);
}
network::~network()
{
networkAccessManager.deleteLater();
}
/**
* #brief network::init
* dns chache warming for all hosts and pre-connecting to all hosts via 4 sockets
*/
void network::init()
{
QList<QString> tcpHosts = provideTcpHosts();
QList<QString> sslHosts = provideSslHosts();
// tcp hosts initialazation
for( int i=0; i<tcpHosts.count(); ++i )
{
// pre-dns lookup cache warming
QHostInfo::lookupHost(tcpHosts[i], 0, 0);
qDebug() << "pre-dns lookup cache warming for: " + tcpHosts[i];
// tcp pre-handshake with known hosts over 4 sockets with known http hosts
for(int a=0; a<4; ++a)
{
networkAccessManager.connectToHost(tcpHosts[i], 80);
qDebug() << "connecting " + QString::number(a+1) + "th socket for " + tcpHosts[i];
}
}
// tcp hosts initialazation
for( int i=0; i<sslHosts.count(); ++i )
{
// pre-dns lookup cache warming
QHostInfo::lookupHost(sslHosts[i], 0, 0);
qDebug() << "pre-dns lookup cache warming for: " + sslHosts[i];
// tcp pre-handshake with known hosts over 4 sockets with known http hosts
for(int a=0; a<4; ++a)
{
networkAccessManager.connectToHostEncrypted(sslHosts[i], 443);
qDebug() << "connecting " + QString::number(a+1) + "th socket for " + sslHosts[i];
}
}
}
/**
* #brief network::replyFinished
* storing previous ssl session tickets for re-use, and error handling for finished requests
* #param url
* #param reply
*/
void network::replyFinished(QUrl &url, QNetworkReply *reply)
{
if(!usedSession.contains((QString)url.toString()))
{
usedSession.insert((QString)url.toString(), (QByteArray)reply->sslConfiguration().sessionTicket());
qDebug() << "saved ssl session ticket for" + url.toString();
}
reply->deleteLater();
}
/**
* #brief network::sendGet
* sending a simple GET request to specified url
* #param url
*/
void network::sendGet(const QUrl &url)
{
connect(&networkAccessManager, SIGNAL(finished(QNetworkReply*)), &eventLoop, SLOT(quit()));
qDebug() << "Sending a GET request to" + (QString)url.toString();
QNetworkRequest request;
request.setUrl(url);
request.setRawHeader("User-Agent", "nebula");
// reusing an ssl session ticket if exists for url
if(usedSession.contains((QString)url.toString()))
{
QSslConfiguration qssl;
qssl.setSslOption(QSsl::SslOptionDisableSessionPersistence, false);
qssl.setSessionTicket(usedSession.value((QString)url.toString()));
request.setSslConfiguration(qssl);
qDebug() << "used ssl session ticket for" + url.toString();
}
reply = networkAccessManager.get(request);
connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(httpError()));
connect(reply, SIGNAL(sslErrors(QList<QSslError>)), this, SLOT(sslErrors(QList<QSslError>)));
connect(reply, SIGNAL(finished()), this, SLOT(httpFinished()));
}
/**
* #brief network::provideTcpHosts
* #return
*/
QList<QString> network::provideTcpHosts()
{
return QList<QString>()
<< (QString)"http://www.google.com"
<< (QString)"http://www.bing.com";
}
/**
* #brief network::provideSslHosts
* #return
*/
QList<QString> network::provideSslHosts()
{
return QList<QString>()
<< (QString)"https://www.ssllabs.com/ssltest/";
}
/*SLOTS*/
/**
* #brief network::slotTcpError
* #param tcpError
*/
void network::httpError()
{
qDebug() << "QNetworkRequest::HttpStatusCodeAttribute " << reply->attribute(QNetworkRequest::HttpStatusCodeAttribute ) << "received";
qDebug() << reply->errorString();
reply->deleteLater();
}
/**
* #brief network::slotSslErrors
* #param sslErrors
*/
void network::sslErrors(const QList<QSslError> &errors)
{
QString errorString;
foreach (const QSslError &error, errors) {
if (!errorString.isEmpty())
errorString += ", ";
errorString += error.errorString();
}
qDebug() << "ssl error recieved: " + errorString;
reply->deleteLater();
}
void network::httpFinished()
{
// possible redirect url
QVariant redirectionTarget = reply->attribute(QNetworkRequest::RedirectionTargetAttribute);
if (!redirectionTarget.isNull()) {
this->sendGet(reply->url().resolved(reply->attribute(QNetworkRequest::RedirectionTargetAttribute).toUrl()));
} else {
qDebug() << "QNetworkRequest::HttpStatusCodeAttribute " << reply->attribute(QNetworkRequest::HttpStatusCodeAttribute ) << "received ";
qDebug() << reply->errorString();
qDebug() << reply->readAll();
}
}
main.cpp
#include <QCoreApplication>
#include <network.h>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
network networkAccessManager;
for(int i = 0; i < 50; ++i)
{
networkAccessManager.sendGet((QString)"http://www.google.com");
}
return a.exec();
}
Please, note I'm quite new to advanced C++ projects and to QT, this project partially -but will be used for my awesome project once its un-screwed- is to help me being familiarized with those topics.
Could you help me out, oh glorious stranger? :)
Regards;
OneEyedSpaceFish

Related

Handeling large QByteArray with QtAudioOutput causes std::bad_alloc

Using QAudioOut Im trying to play data that is stored in a QByteArray in a sequence... this works when there is little data being appended, however when the data gets too much, lets say a 2~3 hour RAW PCM appending from different combinations this data to a QByteArray all at once will result in a std::bad_alloc due to the heap that's not big enough to hold all the data at the same time.
I know where the problem occurs and I think I have a possible solution, its just I have no idea on how to go about implementing it.
Below is a converted function that takes the values in the list
first one 440Hz for 1800000 msec and created RAW PCM square wave. Which works then appends it to a QByteArray then plays it.
This will work if there isn't a lot of appended data form multiple added sequences.
Im looking for a way to do one at a time from the list then create the wave, play that one for x milliseconds then move on to the next entry in the MySeq list. The list can contain large sequences of 3 minute frequencies that runs for hours.
QStringList MySeq;
MySeq << "1:440:180000";
MySeq << "1:20:180000";
MySeq << "1:2120:180000";
MySeq << "1:240:180000";
MySeq << "1:570:180000";
foreach(QString seq, MySeq)
{
QStringList Assits = seq.split(":");
qDebug() << "Now At: " << seq;
QString A = Assits.at(0);
QString B = Assits.at(1);
QString C = Assits.at(2);
qreal amplitude = A.toInt();
float frequency = B.toFloat();
int msecs = C.toInt();
qreal singleWaveTime = amplitude / frequency;
qreal samplesPerWave = qCeil(format->sampleRate() * singleWaveTime);
quint32 waveCount = qCeil(msecs / (singleWaveTime * 1000.0));
quint32 sampleSize = static_cast<quint32>(format->sampleSize() / 8.0);
QByteArray data(waveCount * samplesPerWave * sampleSize * format->channelCount(), '\0');
unsigned char* dataPointer = reinterpret_cast<unsigned char*>(data.data());
for (quint32 currentWave = 0; currentWave < waveCount; currentWave++)
{
for (int currentSample = 0; currentSample < samplesPerWave; currentSample++)
{
double nextRadStep = (currentSample / static_cast<double>(samplesPerWave)) * (2 * M_PI);
quint16 sampleValue = static_cast<quint16>((qSin(nextRadStep) > 0 ? 1 : -1) * 32767);
for (int channel = 0; channel < format->channelCount(); channel++)
{
qToLittleEndian(sampleValue, dataPointer);
dataPointer += sampleSize;
}
}
}
soundBuffer->append(data); // HERE IS THE Std::Bad_Alloc
output->start(outputBuffer);
qDebug() << data.size()
}
I wish to fill the QByteArray with only one sequence at a time then Play it with QAudioOutput then clear the ByteArray then load the next sequence repeat until all sequences are done in the QStringList.
The problem with this approach now is that QAudioOutput is asynchronous and doesn't wait for the first sequence to finish
If I loop over the list as demonstrated above they load one after the other with only the last frequency actually playing. its like the loop keep overwriting the previous sequence.
Im not sure if QEventLoop (Something I haven't used yet) is needed here or Threading. I have tried a couple of different approaches with no success. Any advice would be greatly appreciated. This is a continuation of the following question I had about wave files and data and frequency generations located here
Qt C++ Creating a square audio tone wave. Play and saving it
mainWindows.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QtCore>
#include <QtMultimedia/QAudioOutput>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
public slots:
void playbackFinished();
private slots:
void appendSound();
void on_pushButton_Run_clicked();
void on_pushButton_Stop_clicked();
private:
Ui::MainWindow *ui;
QByteArray *soundBuffer;
QBuffer *outputBuffer;
QAudioFormat *format;
QAudioOutput *output;
};
#endif // MAINWINDOW_H
mainWindows.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>
int sampleRate = 44100;
int channelCount = 2;
int sampleSize = 16;
const QString codec = "audio/pcm";
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
soundBuffer = new QByteArray();
format = new QAudioFormat();
format->setSampleRate(sampleRate);
format->setChannelCount(channelCount);
format->setSampleSize(sampleSize);
format->setCodec(codec);
format->setByteOrder(QAudioFormat::LittleEndian);
format->setSampleType(QAudioFormat::UnSignedInt);
output = new QAudioOutput(*format, this);
connect(output, SIGNAL(stateChanged(QAudio::State)), this, SLOT(playbackFinished()));
outputBuffer = new QBuffer(soundBuffer);
if (outputBuffer->open(QIODevice::ReadOnly) == false) {
qCritical() << "Invalid operation while opening QBuffer. audio/pcm";
return;
}
}
MainWindow::~MainWindow()
{
delete ui;
delete soundBuffer;
delete format;
delete output;
delete outputBuffer;
}
void MainWindow::playbackFinished()
{
if (output->state() == QAudio::IdleState)
{
qDebug() << "Playback finished";
}
}
void MainWindow::appendSound()
{
QStringList MySq;
MySq << "1:440:180000";
MySq << "1:20:180000";
MySq << "1:2120:180000";
MySq << "1:240:180000";
MySq << "1:570:180000";
MySq << "1:570:180000";
MySq << "1:570:180000";
MySq << "1:850:180000";
MySq << "1:1570:180000";
MySq << "1:200:180000";
MySq << "1:50:180000";
MySq << "1:85:180000";
MySq << "1:59:180000";
MySq << "1:20:180000";
foreach(QString seq, MySq)
{
QStringList Assits = seq.split(":");
qDebug() << "Now At: " << seq;
QString A = Assits.at(0);
QString B = Assits.at(1);
QString C = Assits.at(2);
qreal amplitude = A.toInt();
float frequency = B.toFloat();
int msecs = C.toInt();
msecs = (msecs < 50) ? 50 : msecs;
qreal singleWaveTime = amplitude / frequency;
qreal samplesPerWave = qCeil(format->sampleRate() * singleWaveTime);
quint32 waveCount = qCeil(msecs / (singleWaveTime * 1000.0));
quint32 sampleSize = static_cast<quint32>(format->sampleSize() / 8.0);
QByteArray data(waveCount * samplesPerWave * sampleSize * format->channelCount(), '\0');
unsigned char* dataPointer = reinterpret_cast<unsigned char*>(data.data());
for (quint32 currentWave = 0; currentWave < waveCount; currentWave++)
{
for (int currentSample = 0; currentSample < samplesPerWave; currentSample++)
{
double nextRadStep = (currentSample / static_cast<double>(samplesPerWave)) * (2 * M_PI);
quint16 sampleValue = static_cast<quint16>((qSin(nextRadStep) > 0 ? 1 : -1) * 32767);
for (int channel = 0; channel < format->channelCount(); channel++)
{
qToLittleEndian(sampleValue, dataPointer);
dataPointer += sampleSize;
}
}
}
soundBuffer->append(data); // <-- STD::Bad_alloc Not enough memory on heap for appending all the frequencies at once in buffer
output->start(outputBuffer);
qDebug() << data.size();
}
}
void MainWindow::on_pushButton_Run_clicked()
{
appendSound();
}
void MainWindow::on_pushButton_Stop_clicked()
{
output->stop();
soundBuffer->clear();
output->reset();
qDebug() << "Playback Stopped";
}
I came up with a solution using QThread and a Interpreter for that thread to wait for more events before continuing the next sequence in the series.
By doing this I don't need to load the full 3~4 hour PCM data into a QBufferArray all at the same time but rather break it up. Run a smaller sequence then wait on the thread to finish then load the next sequence in line and so on until all of them are done playing.
No more std::bad_alloc since the thread only uses around 80mb on the heap at any given time.

Can not send udp packet in QT

all
I want to use QUdpSocket to send udp packet to get config parameter from specific server,but It failed and I can not capture the sending packet using wireshark.here is my code:
CGetConfig.cpp:
CGetConfig::CGetConfig(const QString &conf_server,const uint16_t port)
:m_conf_server(conf_server)
,m_port(port)
{
m_socket = NULL;
}
CGetConfig::~CGetConfig()
{}
void CGetConfig::init()
{
// create a QUDP socket
m_socket = new QUdpSocket(this);
m_socket->bind(QHostAddress::LocalHost, 12345);
connect(m_socket, SIGNAL(readyRead()), this, SLOT(readyRead()));
m_ip_addr = get_ip_address(m_conf_server);
}
bool CGetConfig::get_reflector(const QString &mac)
{
qDebug() << "CGetConfig::get_reflector():Entry\n";
if(m_ip_addr.isEmpty())
{
qDebug() << "CGetConfig::get_reflector():ip address of cofnig server could not be resolved\n";
return 0;
}
QString msg("id=1&mac=");
msg+= mac;
msg+= "&get_config=fw_type=v.1,cfg_ver=4,set_ver=0,ip=192.168.1.101";
qDebug() << m_ip_addr;
qDebug() << m_port;
qDebug() << msg.toLatin1();
int count = 0;
while(count < 3)
{
int t = m_socket->writeDatagram(msg.toLatin1(), QHostAddress(m_ip_addr), m_port);
count++;
}
}
Main.cpp
CGetConfig cfg(cfg_server,cfg_port);
cfg.init();
local_mac = "00d033120001";
cfg.get_reflector(local_mac);
Can anyone help me figure out the problem?

Qt with ZeroMQ publish subscribe pattern

I would like to use ZeroMQ(4.1.2) with Qt (5.2.1).
Idea is to have zmq pub/sub (where server is outside) and sub is qt app.
Currently receive in Qt app runs once, could someone drop hint?
Should ZeroMQ receiver be implemented in some other way?
Currently my code looks like:
mainwindow.h
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
private slots:
void on_pushButton_clicked();
void readZMQData();
private:
Ui::MainWindow *ui;
QSocketNotifier *qsn;
void *context;
void *subscriber;
};
mainwindow.cpp
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
/***** ZMQ *****/
context = zmq_ctx_new ();
subscriber = zmq_socket (context, ZMQ_SUB);
int rc = zmq_connect (subscriber, "tcp://localhost:5556");
char *filter = "";
rc = zmq_setsockopt (subscriber, ZMQ_SUBSCRIBE,filter, strlen (filter));
unsigned int fd=0;
size_t fd_size = sizeof(fd);
rc = zmq_getsockopt(subscriber,ZMQ_FD,&fd,&fd_size);
qsn = new QSocketNotifier(fd, QSocketNotifier::Read, this);
connect(qsn, SIGNAL(activated(int)), this, SLOT(readZMQData()), Qt::DirectConnection);
}
MainWindow::~MainWindow()
{
zmq_close (this->subscriber);
zmq_ctx_destroy (this->context);
delete ui;
}
void MainWindow::readZMQData()
{
qsn->setEnabled(false);
qDebug() << "Got data!";
int events = 0;
std::size_t eventsSize = sizeof(events);
zmq_getsockopt(subscriber,ZMQ_EVENTS, &events, &eventsSize);
if(events & ZMQ_POLLIN){
qDebug() << " ====== Data to read ======";
char *string = s_recv(subscriber);
qDebug() << "DATA: " << string;
free(string);
}
qsn->setEnabled(true);
}
And server app is (from ZeroMQ examples):
#include "zhelpers.h"
int main (void)
{
// Prepare our context and publisher
void *context = zmq_ctx_new ();
void *publisher = zmq_socket (context, ZMQ_PUB);
int rc = zmq_bind (publisher, "tcp://*:5556");
assert (rc == 0);
// Initialize random number generator
srandom ((unsigned) time (NULL));
while (1) {
// Get values that will fool the boss
int zipcode, temperature, relhumidity;
zipcode = randof (100000);
temperature = randof (215) - 80;
relhumidity = randof (50) + 10;
// Send message to all subscribers
char update [20];
sprintf (update, "%05d %d %d", zipcode, temperature, relhumidity);
s_send (publisher, update);
}
zmq_close (publisher);
zmq_ctx_destroy (context);
return 0;
}
First tnx for helping out,
I've found the issue, when ZeroMQ notifies that there is message to read you need to read them all, not just first one.
void MainWindow::readZMQData(int fd)
{
qsn->setEnabled(false);
int events = 0;
std::size_t eventsSize = sizeof(events);
zmq_getsockopt(subscriber,ZMQ_EVENTS, &events, &eventsSize);
if(events & ZMQ_POLLIN){
qDebug() << " ====== Data to read ======";
char *string;
// THIS IS THE TRICK! READ UNTIL THERE IS MSG
while((string = s_recv_nb(subscriber)) != NULL){
qDebug() << "DATA: " << string;
free(string);
}
}
qsn->setEnabled(true);
}
The socket notifier looks like it should work. Have you read the docs on handling it properly? Especially if you are on Windows, it looks like there are special ways to handle it when doing the read... disabling, reading, etc.
http://doc.qt.io/qt-5/qsocketnotifier.html#details
Hope that helps.
As it is not clear what s_recv_nb(zmq::socket_t & socket) is, I'll provide my - slightly more detailed - implemetation of:
void MainWindow::readZMQData()
{
qsn->setEnabled(false);
int events = 0;
std::size_t eventsSize = sizeof(events);
zmq_getsockopt(subscriber,ZMQ_EVENTS, &events, &eventsSize);
if(events & ZMQ_POLLIN){
qDebug() << " ====== Data to read ======";
char *string;
int64_t more;
size_t more_size = sizeof (more);
do {
/* Create an empty ØMQ message to hold the message part */
zmq_msg_t part;
int rc = zmq_msg_init (&part);
assert (rc == 0);
rc = zmq_msg_recv (&part, subscriber, 0);
assert (rc != -1);
/* Determine if more message parts are to follow */
rc = zmq_getsockopt (subscriber, ZMQ_RCVMORE, &more, &more_size);
assert (rc == 0);
string = (char*) zmq_msg_data(&part);
qDebug() << QString(string) ; // << "more" << more;
zmq_msg_close (&part);
} while (more);
}
qsn->setEnabled(true);
}
And one more remark: in case of Windows 64 the filedescriptor fdshould be uint64_t as in zmq_getsockopt returns EINVAL on windows x64 when local address of ZMQ_FD option_val passed

Proper way to handle multiple QNetworkRequests

im grabbing url's from a list and then sending each to a QNetworkRequest and recieving the HTML back to process. I however have thousands of requests to process. So my application kept hanging until i stopped it from producing all these requests at once.
Is this the rite way to handle the que for a great number of requests?
I tried using a Qqueue of Urls, which i would then link to a SLOT which was triggered after each QNetworkReply reponse.
Create the job list and add to que
QQueue<QString> jobs;
for (int i = 1; i <= totalPages; i++){
QString pageUrl = url + "&page=" + QString::number(i);
jobs.enqueue(pageUrl);
}
qDebug() << "Total Jobs : " << jobs.count() << endl;
for (int i = 0; i < 5; i++){
processQueue();
}
then inside the getHtml function
QNetworkAccessManager *manager = new QNetworkAccessManager(this);
QNetworkRequest *getHtmlRequest = new QNetworkRequest(pageUrl);
getHtmlRequest = new QNetworkRequest(url);
getHtmlRequest->setRawHeader( "User-Agent", "Mozilla/5.0 (X11; U; Linux i686 (x86_64); "
"en-US; rv:1.9.0.1) Gecko/2008070206 Firefox/3.0.1" );
getHtmlRequest->setRawHeader( "charset", "utf-8" );
getHtmlRequest->setRawHeader( "Connection", "keep-alive" );
connect(manager, SIGNAL(finished(QNetworkReply*)), this, SLOT(replyGetPageHtmlFinished(QNetworkReply*)));
connect(manager, SIGNAL(finished(QNetworkReply*)), this, SLOT(processQueue()));
manager->get(*getHtmlRequest);
which triggers
void checkNewArrivalWorker::processQueue(){
if (jobs.isEmpty()){
qDebug() << "Jobs Completed" << endl;
emit finished();
} else {
QString pageUrl = jobs.dequeue();
QString pageNumber = pageUrl.mid(pageUrl.indexOf("page=") + 5);
getHtml(pageUrl, pageNumber);
}
}

The connect (in a QT project) doesn't work

I'm starting to create my first multithread application, using the QT libraries.
Following the qt guide about QTcpServer and QTcpSocket, i wrote a server application that create the connection with this constructor:
Connection::Connection(QObject *parent) : QTcpServer(parent)
{
server = new QTcpServer();
QString ipAddress;
if (ipAddress.isEmpty())
ipAddress = QHostAddress(QHostAddress::LocalHost).toString();
if (!server->listen(QHostAddress(ipAddress),41500))
{
qDebug() << "Enable to start server";
server->close();
return;
}
connect(server,SIGNAL(newConnection()),this,SLOT(incomingConnection()));
}
This is the incomingConnection() function which create a new thread everytime a new client try to connect:
void Connection::incomingConnection()
{
QTcpSocket *socket = new QTcpSocket();
socket = this->nextPendingConnection();
MyThreadClass *thread = new MyThreadClass(socket, server);
qDebug() << "connection required by client";
if (thread != 0)
{
connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));
thread->start();
}
else
qDebug() << "Error: Could not create server thread.";
}
Now, this is MyThreadClass:
MyThreadClass::MyThreadClass(QTcpSocket *socket, QTcpServer *parent) : QThread(parent)
{
tcpSocket = new QTcpSocket();
database = new Db();
blockSize = 0;
tcpSocket = socket;
qDebug() << "creating new thread";
}
MyThreadClass::~MyThreadClass()
{
database->~Db();
}
void MyThreadClass::run()
{
qDebug() << "Thread created";
connect(tcpSocket, SIGNAL(readyRead()), this, SLOT(dataAvailable()));
exec();
}
void MyThreadClass::dataAvailable()
{
qDebug() << "data available";
QDataStream in(tcpSocket);
in.setVersion(QDataStream::Qt_4_0);
if (blockSize == 0) {
if (tcpSocket->bytesAvailable() < (int)sizeof(qint16))
return;
in >> blockSize;
}
if (tcpSocket->bytesAvailable() < blockSize)
return;
QString string;
in >> string;
//[...]
}
The code compiles fine but when i start a client (after starting the server), i receive the following error by server:
QObject::connect: Cannot connect (null)::readyRead() to QThread::dataAvailable()
Then the server cannot receive data by the client.
does anyone have any idea?
thanks in advance
Daniele
socket = this->nextPendingConnection();
should be:
socket = server->nextPendingConnection();
because you are using the server member and not this as the active QTcpServer, the class Connection shouldn't even inherit from QTcpServer, but only from QObject.
Also, you are misusing QThread. You should read Signals and slots across threads, and probably Threads and the SQL Module, if Db is using the QtSql module.