Thread sending http request using Qt - c++

I am trying to create a thread (HttpWorker) that when required wakes up and sends a http request. I would like this to be done in a single thread. I am using Qt for the implementation.
The way I thought i would do it is to have a class MyHttpWorker, move it to another thread, connect the slots/signals etc. Then on thread start I would use QNetworkAccessManager to call get requests. I would use QWaitCondition to pause the thread after the request has been sent and I would resume this thread whenever I need to send another one.
However, when I pause the httpworker thread, the FinishedSlot is not called at all. If I use the class to simply call one http request, it executes with no problem. So the problem is connected to QWaitCondition (or just freezing the threads in general).
I could simply create and destroy one worker and thread for each request I have, but I require to send lot of http requests, so I think this method would be way too consuming (creating threads and destroying them over and over).
I appreciate any help I can get.
Here is my code:
MyHttpWorker.h
#include <QNetworkReply>
#include <QDebug>
#include <QObject>
#include <QNetworkAccessManager>
#include <QThread>
#include <QWaitCondition>
#include <QMutex>
class MyHttpWorker : public QObject
{
Q_OBJECT
QNetworkAccessManager* nam;
QMutex syncPause;
QWaitCondition pauseCond;
public:
explicit MyHttpWorker(QObject *parent = 0);
void MyWake();
public slots:
void SetTheThread(QThread* thread);
void MyStart();
void finishedSlot(QNetworkReply* reply);
};
MyHttpWorker.cpp
MyHttpWorker::MyHttpWorker(QObject *parent) :
QObject(parent)
{
nam = new QNetworkAccessManager(this);
QObject::connect(nam, SIGNAL(finished(QNetworkReply*)), this, SLOT(finishedSlot(QNetworkReply*)));
}
void MyHttpWorker::finishedSlot(QNetworkReply* reply)
{
qDebug() << "Finished"; //This slot is never even reached, when i used QWaitCond...
if (reply->error() == QNetworkReply::NoError)
{
QByteArray bytes = reply->readAll();
QString string(bytes);
qDebug() << string;
}else
{
qDebug() << reply->errorString();
}
reply->deleteLater();
}
void MyHttpWorker::SetTheThread(QThread* thread){
QObject::connect(thread,SIGNAL(started()),this,SLOT(MyStart()));
}
void MyHttpWorker::MyWake(){
pauseCond.wakeAll();
}
void MyHttpWorker::MyStart(){
qDebug() << "Start" ;
while(true){
syncPause.lock();
qDebug() << "thread waiting...";
pauseCond.wait(&syncPause);
qDebug() << "thread resumed.";
syncPause.unlock();
//sending the actual request here
QNetworkRequest myRequest;
myRequest.setUrl(QUrl("http://www.google.com"));
nam->get(myRequest);
}
}
main.cpp
#include <QCoreApplication>
#include <QThread>
#include <QDebug>
#include <myhttpworker.h>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
//create the worker, thread and launch it... (worker is waiting by default)
MyHttpWorker* worker = new MyHttpWorker;
QThread* httpThread = new QThread;
worker->SetTheThread(httpThread);
worker->moveToThread(httpThread);
httpThread->start();
//try and send 5 requests ...
for(int i=0;i<5;i++){
qDebug() << "Unpausing";
QThread::currentThread()->msleep(1000);
worker->MyWake();
}
return a.exec();
}

don't create an infinite loop but let the even loop handle it:
void MyHttpWorker::MyWake()
{
QMetaObject::invokeMethod(this,"doSend");
//send to the event loop
}
// new slot
void MyHttpWorker::doSend(){
//sending the actual request here
QNetworkRequest myRequest;
myRequest.setUrl(QUrl("http://www.google.com"));
nam->get(myRequest);
}
//and remove the myStart and all that synchronisation
then when you want to stop it just send a quit to the thread. I suggest you also connect the finished signal of the thread to the deleteLater slot of MyHttpWorker

Related

unable to send message from client to server

I am writing a client server program that server is multi thread , The code compile without any error, but it doesn't show any message from client.
just it run up to the "qDebug() << " Client connected";"
Here is my code .I would be grateful if you can say where is the problem.
myclient.cpp
#include "myclient.h"
#include "QTcpsocket"
#include "QTcpServer"
#include "mainwindow.h"
#include "QHostAddress"
myclient::myclient(QObject* parent): QObject(parent)
{
}
void myclient::start(QString address, quint16 port)
{
QHostAddress LocalHost;
LocalHost.setAddress(address);
m_client.connectToHost(LocalHost, 6666);
QObject::connect(&m_client, SIGNAL(connected()),this, SLOT(startTransfer()));
}
void myclient::startTransfer()
{
m_client.write("Hello", 5);
}
mythread.cpp
#include "mythread.h"
#include "myserver.h"
mythread::mythread(QTcpSocket*, QObject *parent) :
QThread(parent)
{
}
void mythread::run()
{
qDebug() << " Thread started";
if (m_client)
{
connect(m_client, SIGNAL(connected()), this, SLOT(readyRead()), Qt::DirectConnection);
}
qDebug() << " Client connected";
exec();
}
void mythread::readyRead()
{
QByteArray Data = m_client->readAll();
qDebug()<< " Data in: " << Data;
m_client->write(Data);
}
void mythread::disconnected()
{
qDebug() << " Disconnected";
m_client->deleteLater();
exit(0);
}
myserver.cpp
#include "myserver.h"
#include "mythread.h"
myserver::myserver(QObject *parent) :
QObject(parent)
{
}
void myserver::startserver()
{
connect(&m_server,SIGNAL(newConnection()), this ,SLOT(newConnection()));
int port = 6666;
if(m_server.listen(QHostAddress::Any, port))
{
qDebug() << "Listening to port " ;
}
else
{
qDebug() << "Could not start server "<<m_server.errorString();
}
}
void myserver::newConnection()
{
m_client = m_server.nextPendingConnection();
qDebug() << " Connecting...";
mythread *thread = new mythread(m_client,this);
thread->start();
}
Documentation about nextPendingConnection() says:
Note: The returned QTcpSocket object cannot be used from another
thread. If you want to use an incoming connection from another thread,
you need to override incomingConnection().
So, you can't use that socket in another thread. As the docs say, you can subclass QTcpServer and override incomingConnection(), this method is invoked whenever a client tries to connect to your server.
incomingConnection() method provides a socket descriptor (just like regular file descriptors). And then you can pass that socket descriptor to another thread and create the QTcpSocket completely over there.
Inside that thread, you would need something like this:
QTcpSocket client = new QTcpSocket();
client.setSocketDescriptor(sockId);
// Now, you can use this socket as a connected socket.
// Make sure to connect its ready read signal to your local slot.
Once you get in newConnection the client is already connected, and you just need to start a thread that calls readAll and then replies.
There's no need to wait for a connected() signal again.
EDIT
The QSocket class is designed to work asynchronously on the main thread, based on events. From the documentation:
Warning: QSocket is not suitable for use in threads. If you need to uses sockets in threads use the lower-level QSocketDevice class.

Crashing of application QT(ftp downloading with progressbar)

I want to create a application, by this i can download the file from my ftp server
and show the progress in progressbar. Ive wrote some code, but if im clicking on the button to download the file from ftp server, my application is crashing. Ive become some qDebug answers like:
"no errors request",
"updateDataTransferProgress started"
the file which must be downloaded was created in a folder, but the file is empty.:( What can u do to fix my problem?
Many thanks!
#include "f1.h"
#include "ui_f1.h"
#include "ui_form2.h"
#include "form2.h"
#include <QNetworkAccessManager>
#include <QFile>
#include <QFtp>
#include <QtNetwork>
#include <QMessageBox>
f1::f1(QWidget *parent) :
QFrame(parent),
ui(new Ui::f1)
{
ui->setupUi(this);
// ui->progressBar->setValue(0);
connect(ui->pushButton,SIGNAL(clicked()),this,SLOT(onDownServ()));
}
void f1::closeEvent(QCloseEvent *event)
{
F2->helloWorld();
}
f1::~f1()
{
delete ui;
}
void f1::onDownServ()
{
QNetworkAccessManager *nam = new QNetworkAccessManager();
QUrl url2("ftp://test.cz/plugins.txt");
url2.setPassword("test");
url2.setUserName("test");
reply = nam->get(QNetworkRequest(url2));
connect(reply, SIGNAL(readyRead()), this, SLOT(readyRead()));
connect(reply, SIGNAL(downloadProgress(qint64, qint64)),this, SLOT(updateDataTransferProgress(qint64,qint64)));
connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), SLOT(requestError(QNetworkReply::NetworkError)));
connect(reply, SIGNAL(finished()), this, SLOT(requestFinished()));
}
void f1::requestFinished()
{
qDebug() << "finished !";
save->flush();
save->close();
}
void f1::requestError(QNetworkReply::NetworkError)
{
qDebug() << "no errors, request";
}
void f1::readyRead()
{
qDebug() << "ready read!";
save=new QFile("plugins.txt");
if (!save->open(QIODevice::WriteOnly))
return;
save->write(reply->readAll());
}
void f1::updateDataTransferProgress(qint64 done, qint64 total)
{
qDebug() << "updateDataTransferProgress started";
ui->progressBar->setMaximum(100);
ui->progressBar->setValue(done*100/total);
}
QNetworkReply is a sequential-access QIODevice in which whenever more data is received from the network, the readyRead() signal is emitted. So your readyRead() slot will probably get called multiple times as new data comes gradually. So you should not initialize your file in that slot. The file initialization should be done in onDownServ() slot once:
QNetworkAccessManager *nam = new QNetworkAccessManager();
QUrl url2("ftp://test.cz/plugins.txt");
url2.setPassword("test");
url2.setUserName("test");
save=new QFile("plugins.txt");
if (!save->open(QIODevice::WriteOnly))
return;
reply = nam->get(QNetworkRequest(url2));
When you do file initialization in readyRead() slot, it opens file in the first call and subsequent calls are returned as it can not open the new file for write operation. So the readyRead() slot gets called repeatedly and the application crashes.

Running function in Qthread - The application will hang

I have some problems with threading inside QT.
#include <QCoreApplication>
#include "handler.hpp"
int main(int argc, char *argv[]) {
QCoreApplication a(argc, argv);
Handler* handler = new Handler();
handler->StartThread();
return a.exec();
}
What I expect is that with handler->StartThread() statement the function within my thread start to write debug messages and once the internal timer within handler finishes I get the nice line [Press ...] and then a return code of 0. However this is not happening. What I get is:
I WORK... ( 0x1540 )
Worker has finished. ( 0x6f4 )
I WORK... ( 0x1540 )
Worker has finished. ( 0x6f4 )
I WORK... ( 0x1540 )
Worker has finished. ( 0x6f4 )
I WORK... ( 0x1540 )
Worker has finished. ( 0x6f4 )
Thread stopped.
And of course when I stop the execution of the application, the return code is: -1073741510. Obviously not that nice of a zero.
Anyway here's the rest of the application code:
Handler.hpp
#ifndef HANDLER_HPP
#define HANDLER_HPP
#include <QObject>
#include <QThread>
#include <QDebug>
#include <QTimer>
#include "testclass.hpp"
class Handler : public QObject
{
Q_OBJECT
public:
Handler();
~Handler();
void StartThread();
public slots:
void functionFinished();
void threadTerminated();
private:
QTimer* shutdown;
QTimer* timer;
QThread* thread;
MyClass* worker;
};
#endif // HANDLER_HPP
Handler.cpp
#include "handler.hpp"
Handler::Handler() {
shutdown = new QTimer();
thread = new QThread();
timer = new QTimer();
worker = new MyClass();
worker->moveToThread(thread);
QObject::connect(thread, SIGNAL(started()), worker, SLOT(runAgain()));
QObject::connect(timer, SIGNAL(timeout()), worker, SLOT(runAgain()));
QObject::connect(worker, SIGNAL(iFinished()), this, SLOT(functionFinished()));
QObject::connect(shutdown, SIGNAL(timeout()), thread, SLOT(quit()));
QObject::connect(thread, SIGNAL(finished()), this, SLOT(threadTerminated()));
shutdown->start(20000);
}
Handler::~Handler() {
QObject::disconnect(thread, SIGNAL(started()), worker, SLOT(runAgain()));
QObject::disconnect(timer, SIGNAL(timeout()), worker, SLOT(runAgain()));
QObject::disconnect(worker, SIGNAL(iFinished()), this, SLOT(functionFinished()));
QObject::disconnect(shutdown, SIGNAL(timeout()), thread, SLOT(quit()));
QObject::disconnect(thread, SIGNAL(finished()), this, SLOT(threadTerminated()));
if (shutdown != 0) {
delete shutdown;
shutdown = 0;
}
if (timer != 0) {
delete timer;
timer = 0;
}
if (thread != 0) {
delete thread;
thread = 0;
}
if (worker != 0) {
delete worker;
worker = 0;
}
}
void Handler::functionFinished() {
qDebug() << "Worker has finished. (" << QThread::currentThreadId() << ")";
timer->start(5000);
}
void Handler::threadTerminated() {
qDebug() << "Thread stopped.";
}
void Handler::StartThread() {
thread->start();
}
MyClass (header - testclass.hpp)
#ifndef TESTCLASS_HPP
#define TESTCLASS_HPP
#include <QTimer>
#include <QObject>
class MyClass : public QObject
{
Q_OBJECT
public:
MyClass();
public slots:
void runAgain();
signals:
void iFinished();
private:
void doWork();
};
#endif // TESTCLASS_HPP
MyClass Source - testclass.cpp
#include "testclass.hpp"
#include <QThread>
#include <QDebug>
MyClass::MyClass() {
}
void MyClass::runAgain() {
doWork();
}
void MyClass::doWork() {
qDebug() << "I WORK...\t(" << QThread::currentThreadId() << ")";
emit iFinished();
}
I've previosly read that it's not a good idea to inherit the classes to be ran inside a thread directly from QThread and so I came up with this solution but it still gets fishy though it's pretty nice. I'm open to any recommendation, this is my first time with QT so better to learn now than feel sorry later.
Oh my bad, I forgot the concrete actual question. Why doesn't the execution ends with a nice exit code of 0?
What I expect is that with handler->StartThread() statement the function within my thread start to write debug messages and once the internal timer within handler finishes I get the nice line [Press ...] and then a return code of 0. However this is not happening.
The reason you're not getting a finished command prompt of "[Press ...]" is due to the QCoreApplication and its exec() call. As the Qt docs state: -
Enters the main event loop and waits until exit() is called
So, you've created a second thread, set it to do some work and finish, but the main thread is still running. You need to exit the main thread.
And of course when I stop the execution of the application, the return code is: -1073741510
It sounds like you're killing the main thread with something like "Ctrl+C". Calling QCoreApplication::exit() when your 2nd thread finishes and has cleaned up, should help here.

Qt c++ double emit Data

I have a multiserverapp that works fine so far. I got 4 cpp files.
Main.cpp constructs the program. MainWindow.cpp constructs the ui and starts (via buttonclick) MyServer.cpp. MyServer.cpp creates a thread and starts MyThread.cpp.
My aim is to show several major steps (like the "server started", "new connection", etc..) on a textBrowser.
I pass the outputs from MyServer.cpp via emit updateUI("server started"); to mainwindow.cpp where the output gets catched by:
//Mainwindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "myserver.h"
#include "mythread.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::AppendToBrowser(const QString text)
{
ui->textBrowser->append(text);
}
void MainWindow::on_startButton_clicked()
{
MyServer* mServer = new MyServer;
connect(mServer, SIGNAL(updateUI(const QString)), this, SLOT(AppendToBrowser(const QString)));
mServer->StartServer();
ui->textBrowser->setPlainText("Server Started");
}
That works just right because the connect command is just in the mainwindow.cpp itself.
The problem starts one step "deeper" in the mythread.cpp.
I created another signal in the
//MyThread.h
signals:
void updateUI_serv(const QString text);
and connected it in the MyServer.cpp with the MainWindow.cpp.
//MyServer.cpp
#include "myserver.h"
#include "mainwindow.h"
MyServer::MyServer(QObject *parent) :
QTcpServer(parent)
{
}
void MyServer::StartServer()
{
if(!this->listen(QHostAddress::Any,1234))
{
qDebug("Server Error");
}
else
{
qDebug("Server started");
}
}
void MyServer::incomingConnection(int socketDescriptor)
{
qDebug("new connection");
MyThread *thread = new MyThread(socketDescriptor,this);
MainWindow *mMain = new MainWindow;
connect(thread, SIGNAL(updateUI_serv(const QString)),mMain ,SLOT(AppendToBrowser(const QString)));
//flags thread for selfdeletion
connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));
//calls run
thread->start();
emit updateUI("thread started!");
}
// MyThread.cpp
#include "mythread.h"
#include "mainwindow.h"
#include "myserver.h"
MyThread::MyThread(int ID, QObject *parent) :
QThread(parent)
{
this->socketDescriptor = ID;
emit updateUI_serv("start");
}
void MyThread::run()
{
//thread stars here
qDebug("Starting thread");
socket = new QTcpSocket();
emit updateUI_serv("hallo");
//set socketdescriptor number
if(!socket->setSocketDescriptor(this->socketDescriptor))
{
emit error(socket->error());
return;
}
connect(socket, SIGNAL(readyRead()), this, SLOT(readyRead()), Qt::DirectConnection);
connect(socket, SIGNAL(disconnected()), this, SLOT(disconnected()), Qt::DirectConnection);
qDebug("client connected");
exec();
}
void MyThread::readyRead()
{
QByteArray Data = socket->readAll();
QString Datain = QString::fromLatin1(Data);
qDebug("Date in:");
emit updateUI_serv("data in:");
socket->write(Data);
}
void MyThread::disconnected()
{
qDebug("Disconnected");
socket->deleteLater();
exit(0);
}
The connect command lays here "in between" the signal (updateUI_serv from mythread.cpp) and the slot (AppendToBrowser from mainwindow.cpp) file.
At this point the program crashes as soon as I try to write data (as a client via telnet) to the serverapp.
I tried to set the connect command into the mainwindow and the mythread as well, but both times I get different problems (like debugging problems, or the text does just not show up in the textBrowser).
Thanks so far.
Eventually the myServer-Object is not running in the MainThread, therefor accessing an ui element from another thread crashes your app.
You can make sure only Messages from mainThread will get displayed by adding the following code to your AppendToBrowser Slot:
if( QApplication::instance()->thread() == QThread::currentThread() )
ui->textBrowser->setPlainText("whateverTextThereShallBe");
else
return;
//You should not run into this else...
This if section checks if the current object calling the update is the mainThread. The else-section checks for erros. If you are running in the else-section you are trying to change ui-elements form a thread which is not the mainThread (UI-Thread). Connect your SIGNAL in server to another SIGNAL (SIGNAL->SIGNAL connection) and add a connect to SIGNAL(SERVER) -> SLOT(MainWindow) in your MainWindow.cpp. Eventually try your connect-call with the 5th. parameter for Queued Connection (Qt::QueuedConnection IIRC).
Ahh i got it on my own.
I solved the problem by creating a NEW function ( void forwarding(const Qstring); ) and in that function i emitted it with the ordinary emit updateUI(text); .. stuff works finaly!

Server thread inside a qt class (need mutex?)

I made this server class that starts a thread when new connection comes in. It works ok with some cases, but it's not very stable. I am trying to solve where it breaks. My debugger tells me something about qmutex. If anyone can spot the problem. ty
It connects with parent with signal&slots and gets data back also.
Here is the header:
#ifndef FORTUNESERVER_H
#define FORTUNESERVER_H
#include <QStringList>
#include <QTcpServer>
#include <QThread>
#include <QTcpSocket>
#include <string>
using namespace std;
class FortuneServer : public QTcpServer
{
Q_OBJECT
public:
FortuneServer(QObject *parent = 0);
public slots:
void procesServerString(string serverString);
void getStringToThread(string serverString);
protected:
void incomingConnection(int socketDescriptor);
private:
QStringList fortunes;
signals:
void procesServerStringToParent(string serverString);
void getStringToThreadSignal(string serverString);
};
class FortuneThread : public QObject
{
Q_OBJECT
public:
FortuneThread(int socketDescriptor, QObject *parent);
public slots:
void getString();
void sendString(string sendoutString);
signals:
void error(QTcpSocket::SocketError socketError);
void fromThreadString(string serverString);
void finished();
private:
int socketDescriptor;
QString text;
QTcpSocket tcpSocket;
};
#endif
and cc:
#include <stdlib.h>
#include <QtNetwork>
#include "MeshServer.hh"
#include <iostream>
#include "TableView.hh"
using namespace std;
FortuneServer::FortuneServer(QObject *parent)
: QTcpServer(parent)
{
}
void FortuneServer::procesServerString(string serverString){
emit procesServerStringToParent(serverString);
}
void FortuneServer::getStringToThread(string serverString){
emit getStringToThreadSignal(serverString);
}
void FortuneServer::incomingConnection(int socketDescriptor)
{
FortuneThread *serverthread = new FortuneThread(socketDescriptor, this);
//connect(&serverthread, SIGNAL(finished()), &serverthread, SLOT(deleteLater()));
QThread* thread = new QThread;
serverthread->moveToThread(thread);
connect(thread, SIGNAL(started()), serverthread, SLOT(getString()));
connect(serverthread, SIGNAL(fromThreadString(string)), this, SLOT(procesServerString(string)));
connect(this, SIGNAL(getStringToThreadSignal(string)), serverthread, SLOT(sendString(string)));
connect(serverthread, SIGNAL(finished()), thread, SLOT(quit()));
connect(serverthread, SIGNAL(finished()), serverthread, SLOT(deleteLater()));
connect(serverthread, SIGNAL(finished()), thread, SLOT(deleteLater()));
thread->start();
}
FortuneThread::FortuneThread(int socketDescriptor, QObject *parent)
: QObject(parent), socketDescriptor(socketDescriptor)
{
}
void FortuneThread::getString()
{
if (!tcpSocket.setSocketDescriptor(socketDescriptor)) {
emit error(tcpSocket.error());
cout<<"socket error"<<endl;
return;
}
//in part
if(!tcpSocket.waitForReadyRead(10000)){
emit finished();
return;
}
int joj = tcpSocket.bytesAvailable();
char inbuffer[1024];
tcpSocket.read(inbuffer,1024);
string instring;
instring = inbuffer;
instring.resize(joj);
emit fromThreadString(instring);
}
void FortuneThread::sendString(string sendoutString)
{
//out part
char buffer[1024];
int buffer_len = 1024;
int bytecount;
memset(buffer, '\0', buffer_len);
string outstring = sendoutString;
int TempNumOne= (int)outstring.size();
for (int a=0;a<TempNumOne;a++)
{
buffer[a]=outstring[a];
}
QByteArray block;
block = buffer;
tcpSocket.write(block);
tcpSocket.disconnectFromHost();
tcpSocket.waitForDisconnected();
emit finished();
}
this is from parent:
//server start
QHostAddress adr;
adr.setAddress( QString("127.0.0.1") );
adr.toIPv4Address();
quint16 port = 1101;
if (!server.listen( adr, port)) {
QMessageBox::critical(this, tr("CR_bypasser"),
tr("Unable to start the server: %1.")
.arg(server.errorString()));
close();
return;
}
QString ipAddress;
ipAddress = server.serverAddress().toString();
statusLabel->setText(tr("The server is running on\n\nIP: %1\nport: %2\n\n"
"Run the Fortune Client example now.")
.arg(ipAddress).arg(server.serverPort()));
connect (&server, SIGNAL(procesServerStringToParent(string)), this, SLOT(procesServerString(string)));
connect (this, SIGNAL(StringToServer(string)), &server, SLOT(getStringToThread(string)));
edit: what I am trying to do:
I have a client (part of a game engine(Cryengine)) that I made to send string of ingame coordinates and some other things with a socket like its done in a link I gave before. This works ok. I get data on "127.0.0.1" port 1101. Now I just need this data to be evaluated in my own program, that has this TableView class, inside which I can collect coordinates I get from the string, callculate some data from coordinates and then return this new string back through the server to gameengine. In game I will click on objects get their coor., make a string out of that (containing coor,entityid, etc..), send this string to server, that returns callculated info from TableView. I just need this one way flow only one client that is sending strings. I am not sure about recv(hsock, buffer, buffer_len, 0), I guess node that is responsible for string sending in game will wait for return string? This is one of my first programs atm I am realy confused...
The code you present is exemplary of cargo cult coding: you do various unnecessary things, apparently in hopes of fixing the problem.
The Likely Crasher ...
There are tons of problems with the code, but I think the cause of the crash is this: tcpSocket.write(block) does not send out a zero-terminated string down the wire. The block is zero-terminated, but the assignment to a byte array does not add this zero termination to the size() of QByteArray. The following code prints 1, even though there is a zero terminating byte internally in the contents of the byte array.
QByteArray arr = "a";
qDebug("len=%d", arr.size());
The receiving code expects the zero termination, but never receives it. You then proceed to assign a non-zero-terminated buffer to std::string:
string instring;
instring = inbuffer;
instring.resize(joj);
The subsequent resize is cargo cult: you're trying to fix the problem after std::string & std::string::operator=(const char*) has already read past your buffer, in all likelihood.
Do not take this to mean that fixing just that is the right way to proceed. Not at all. The right way to proceed is to delete the code you wrote and do it right, without a ton of unnecessary incantations that don't help.
... and All The Other Problems
You've fallen into the trap of believing in magic, perpetuated endlessly in various forums.
The threads are not magical objects that you can just apply to any problem out there in hopes that they help. I don't know what makes people think that threads are magical, but the rule of thumb is: If someone tells you "oh, you should try threads", they are most likely wrong. If they tell that in relation to networking, they are pretty much never right, they are unhelpful, and they don't understand your problem at all (neither do you, it seems). More often than not, threads will not help unless you clearly understand your problem. Qt's networking system is asynchronous: it doesn't block the execution of your code, if you don't use the waitxxxx() functions. You shouldn't use them, by the way, so all is good here. No need for a bazillion threads.
So, it is completely unnecessary to start a new thread per each incoming connection. It will decrease the performance of your server -- especially if the server does simple processing because you add the overhead of context switching and thread creation/dismantling to each connection. You want less than 2 threads per each core in your system, so using QThread::idealThreadCount() for the number of threads in the pool would be a good starting point.
You are also depriving yourself of the benefit of threading since you use the networking thread only to receive the data, and you then send out a fromThreadString(string) signal. I presume that signal is sent to your application's main thread. Now that's just silly, because receiving a bunch of bytes from a network socket is downright trivial. Your threads don't do any work, all the work they do is wasted on their creation and removal.
The code below is a simple example of how one might correctly use the Qt APIs to implement a client-server system that distributes work across the physical cores in a round-robin fashion. It should perform quite well. The Fortune client example included in Qt is very unfortunate indeed, because it's precisely the wrong way to go about things.
What one will notice is:
It's not entirely trivial. Qt could be more helpful, but isn't.
Both the clients and the senders are moved into threads from a thread pool.
Disconnected clients are not deleted, but merely returned to a list of clients
kept by the tread pool. They are reused when a client is called for.
QThread is not derived from. QTcpServer is only derived to access the socket handle.
No functions whose name begins with wait() are used. Everything is handled asynchronously.
The ThreadPool keeps a looked-up QMetaMethod for the newConnection(int) slot of the Client. This is faster than using QMetaObject::invokeMethod() as it has to look things up every time.
A timer running in the main thread sets off a signal-slot chain by deleting the first sender. Each senders' deletion triggers the deletion of the next one. Eventually, the last sender sets off the quit() slot in the thread pool. The latter emits the finished() signal when all threads are indeed finished.
#include <QtCore/QCoreApplication>
#include <QtNetwork/QTcpServer>
#include <QtNetwork/QTcpSocket>
#include <QtCore/QQueue>
#include <QtCore/QThread>
#include <QtCore/QTimer>
#include <QtCore/QMetaMethod>
// Processes data on a socket connection
class Client : public QObject
{
Q_OBJECT
public:
Client(QObject* parent = 0) : QObject(parent), socket(new QTcpSocket(this))
{
connect(socket, SIGNAL(readyRead()), SLOT(newData()));
connect(socket, SIGNAL(stateChanged(QAbstractSocket::SocketState)),
SLOT(newState(QAbstractSocket::SocketState)));
qDebug("Client()");
}
~Client() { qDebug("~Client()"); }
signals:
void done();
public slots:
void newConnection(int descriptor) {
socket->setSocketDescriptor(descriptor);
}
private slots:
void newData() {
QByteArray data = socket->readAll();
if (0) qDebug("got %d bytes", data.size());
if (0) qDebug("got a string %s", data.constData());
// here we can process the data
}
void newState(QAbstractSocket::SocketState state) {
qDebug("client new state %d", state);
if (state == QAbstractSocket::UnconnectedState) { emit done(); }
}
protected:
QTcpSocket* socket;
int descriptor;
};
// Connects to a client and sends data to it
class Sender : public QObject
{
Q_OBJECT
public:
Sender(const QString & address, quint16 port, QObject * parent = 0) :
QObject(parent), socket(new QTcpSocket(this)),
bytesInFlight(0), maxBytesInFlight(65536*8)
{
connect(socket, SIGNAL(stateChanged(QAbstractSocket::SocketState)),
SLOT(newState(QAbstractSocket::SocketState)));
connect(socket, SIGNAL(bytesWritten(qint64)), SLOT(sentData(qint64)));
socket->connectToHost(address, port);
qDebug("Sender()");
}
~Sender() { qDebug("~Sender()"); }
protected:
// sends enough data to keep a maximum number of bytes in flight
void sendData() {
qint64 n = maxBytesInFlight - bytesInFlight;
if (n <= 0) return;
bytesInFlight += n;
socket->write(QByteArray(n, 44)); // 44 is the answer, after all
}
protected slots:
void sentData(qint64 n) {
bytesInFlight -= n;
Q_ASSERT(bytesInFlight >= 0);
sendData();
}
void newState(QAbstractSocket::SocketState state) {
qDebug("sender new state %d", state);
if (state == QAbstractSocket::ConnectedState) sendData();
}
protected:
QTcpSocket* socket;
qint64 bytesInFlight;
qint64 maxBytesInFlight;
};
// Keeps track of threads and client objects
class ThreadPool : public QTcpServer
{
Q_OBJECT
public:
ThreadPool(QObject* parent = 0) : QTcpServer(parent), nextThread(0) {
for (int i=0; i < QThread::idealThreadCount(); ++i) {
QThread * thread = new QThread(this);
connect(thread, SIGNAL(finished()), SLOT(threadDone()));
thread->start();
threads << thread;
}
const QMetaObject & mo = Client::staticMetaObject;
int idx = mo.indexOfMethod("newConnection(int)");
Q_ASSERT(idx>=0);
method = mo.method(idx);
}
void poolObject(QObject* obj) const {
if (nextThread >= threads.count()) nextThread = 0;
QThread* thread = threads.at(nextThread);
obj->moveToThread(thread);
}
protected:
void incomingConnection(int descriptor) {
Client * client;
if (threads.isEmpty()) return;
if (! clients.isEmpty()) {
client = clients.dequeue();
} else {
client = new Client();
connect(client, SIGNAL(done()), SLOT(clientDone()));
}
poolObject(client);
method.invoke(client, Q_ARG(int, descriptor));
}
signals:
void finished();
public slots:
void quit() {
foreach (QThread * thread, threads) { thread->quit(); }
}
private slots:
void clientDone() {
clients.removeAll(qobject_cast<Client*>(sender()));
}
void threadDone() {
QThread * thread = qobject_cast<QThread*>(sender());
if (threads.removeAll(thread)) delete thread;
if (threads.isEmpty()) emit finished();
}
private:
QList<QThread*> threads;
QQueue<Client*> clients;
QMetaMethod method;
mutable int nextThread;
};
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
ThreadPool server;
if (!server.listen(QHostAddress::Any, 1101)) qCritical("cannot establish a listening server");
const int senderCount = 10;
Sender *prevSender = 0, *firstSender = 0;
for (int i = 0; i < senderCount; ++ i) {
Sender * sender = new Sender("localhost", server.serverPort());
server.poolObject(sender);
if (!firstSender) firstSender = sender;
if (prevSender) sender->connect(prevSender, SIGNAL(destroyed()), SLOT(deleteLater()));
prevSender = sender;
}
QTimer::singleShot(3000, firstSender, SLOT(deleteLater())); // run for 3s
server.connect(prevSender, SIGNAL(destroyed()), SLOT(quit()));
qApp->connect(&server, SIGNAL(finished()), SLOT(quit()));
// Deletion chain: timeout deletes first sender, then subsequent senders are deleted,
// finally the last sender tells the thread pool to quit. Finally, the thread pool
// quits the application.
return a.exec();
}
#include "main.moc"
Given your explanation, you game engine starts up and creates a connection to some port on localhost. Your Qt program is supposed to accept that connection on port 1101, receive some strings, process them, then send them back.
The code is modified to accept the connection on a fixed port number. All of the data processing, including sending the response back, has to be done from the newData() slot. You can also pass that data off to a different thread, if your computations are very complex. By complex I mean tens of thousands of operations like additions and multiplications, or thousands of trig operations.
The Sender class is there just as an example. Your game engine does the sending, of course, so you don't need the Sender class.
I got my old "the wrong way to do it" code to work. I guess this part was where the error was:
//removed
tcpSocket.disconnectFromHost();
tcpSocket.waitForDisconnected();
emit finished();
...
#include <stdlib.h>
#include <QtNetwork>
#include "MeshServer.hh"
#include <iostream>
#include "TableView.hh"
using namespace std;
FortuneServer::FortuneServer(QObject *parent)
: QTcpServer(parent)
{
}
void FortuneServer::procesServerString(string serverString){
emit procesServerStringToParent(serverString);
}
void FortuneServer::getStringToThread(string serverString){
emit getStringToThreadSignal(serverString);
}
void FortuneServer::incomingConnection(int socketDescriptor)
{
FortuneThread *serverthread = new FortuneThread(socketDescriptor, this);
//connect(&serverthread, SIGNAL(finished()), &serverthread, SLOT(deleteLater()));
QThread* thread = new QThread;
serverthread->moveToThread(thread);
connect(serverthread, SIGNAL(fromThreadString(string)), this, SLOT(procesServerString(string)));
connect(this, SIGNAL(getStringToThreadSignal(string)), serverthread, SLOT(sendString(string)));
connect(serverthread, SIGNAL(finished()), thread, SLOT(quit()));
connect(serverthread, SIGNAL(finished()), serverthread, SLOT(deleteLater()));
connect(serverthread, SIGNAL(finished()), thread, SLOT(deleteLater()));
thread->start();
}
FortuneThread::FortuneThread(int socketDescriptor, QObject *parent): QObject(parent), socketDescriptor(socketDescriptor)
{
if (!tcpSocket.setSocketDescriptor(socketDescriptor)) {
emit error(tcpSocket.error());
cout<<"socket error"<<endl;
emit finished();
return;
}
connect(&tcpSocket, SIGNAL(readyRead()), this, SLOT(getString()));
//connect(&tcpSocket, SIGNAL(disconnected()), this, SLOT(ondisconnected()));
}
void FortuneThread::getString()
{
int joj = tcpSocket.bytesAvailable();
if(joj==0){
tcpSocket.disconnectFromHost();
emit finished();
return;
}
char inbuffer[1024];
int buffer_len = 1024;
memset(inbuffer, '\0', buffer_len);
tcpSocket.read(inbuffer,1024);
string instring;
instring = inbuffer;
instring.resize(joj);
emit fromThreadString(instring);
}
void FortuneThread::sendString(string sendoutString)
{
char buffer2[1024];
int buffer_len = 1024;
memset(buffer2, '\0', buffer_len);
strcat(buffer2,sendoutString.c_str());
tcpSocket.write(buffer2,buffer_len);
}
void FortuneThread::ondisconnected()
{
emit finished();
}