简体   繁体   中英

QT5: Multithread Tcp server doesn't send data to user

I'm new in QT5 and decided to create simple multithreaded tcp server. I've read examples provided in QT but they have additional functions and complexity which I'm trying to avoid at this point. Here is my code:

server.h

#ifndef SERVER_H
#define SERVER_H

#include <QTcpServer>
#include <QTcpSocket>
#include "threadz.h"
class Server : public QTcpServer
{
  Q_OBJECT
  public:
  explicit Server(QObject *parent = 0);

 signals:

 public slots:
  void newConnection();
 private:
  QTcpServer *serv;

};

#endif // SERVER_H



threadz.h

#ifndef THREADZ_H
#define THREADZ_H

#include <QThread>
#include <QDebug>
#include "server.h"
class Threadz : public QThread
{
  Q_OBJECT

  public:
   explicit Threadz(QObject *parent = 0);
   void run(QTcpServer *serv);

  signals:

  public slots:

};

#endif // THREADZ_H



server.cpp

#include "server.h"

Server::Server(QObject *parent) :
   QTcpServer(parent)
{
  serv = new QTcpServer(this);

  connect(serv, SIGNAL(newConnection()), this, SLOT(newConnection()));

  if(!serv->listen(QHostAddress::Any, 1234))
  {
    qDebug() << "Error";
  }

}

void Server::newConnection()
{
   Threadz *thred = new Threadz();
   thred->start();

}



threadz.cpp

#include "threadz.h"
Threadz::Threadz(QObject *parent) :
  QThread(parent)
{
}


void Threadz::run(QTcpServer *serv)
{
  QTcpSocket *socket  = serv->nextPendingConnection();

  socket->write("Hello!r\n");
  socket->waitForBytesWritten();
  socket->close();


}



main.cpp

#include <QCoreApplication>
#include "simplehttp.h"
#include "server.h"
int main(int argc, char *argv[])
{
  QCoreApplication a(argc, argv);

  Server gio;


  return a.exec();
}

Basically, Im trying to create new thread for every client that connects server. But problem is that when I run this code and connect server with telnet 127.0.0.1 1234 nothing is printed on the screen. No errors but nothing is printed neither. Im using ubuntu 14.04. Sorry if question is silly and thanks in advance.

The QThread::run function is not implemented.

void QThread::run() [virtual protected]

The starting point for the thread. After calling start(), the newly created thread calls this function. The default implementation simply calls exec().

You can reimplement this function to facilitate advanced thread management. Returning from this method will end the execution of the thread.

Instead you implemented void Threadz::run(QTcpServer *serv) but something needs to call this function .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM