多线程服务器

时间:2015-12-05 13:04:37

标签: c++ multithreading qt

我正在编写多线程服务器,但我在接受连接和启动读取功能时遇到问题。我不知道我应该把它们写在哪里.. 这是我的代码: “mythread.cpp”

#include "mythread.h"
#include "myserver.h"

mythread::mythread(qintptr ID, QObject *parent) :
QThread(parent)
{
this->socketDescriptor = ID;
}


void mythread::run()
 {

  qDebug() << " Thread started";
 }


void mythread::acceptConnection()
 {

  c_client = s_server.nextPendingConnection();

  connect(c_client,SIGNAL(readyRead()),

   this, SLOT(startRead()));
   }

 void mythread::startRead()
 {

 char buffer[1024] = {0};

 c_client->read(buffer, c_client->bytesAvailable());

 qDebug() << buffer;

 }

 void mythread::readyRead()
 {
QByteArray Data = socket->readAll();

qDebug() << socketDescriptor << " Data in: " << Data;

socket->write(Data);
}

void mythread::disconnected()
 {
qDebug() << socketDescriptor << " Disconnected";


socket->deleteLater();
exit(0);
 }

“myserver.cpp”

#include "myserver.h"
#include "mythread.h"


myserver::myserver(QObject *parent) :

QObject(parent)
{
}

void myserver::startserver()
{
int port = 1234;
if(s_server.listen(QHostAddress::Any, port))
{
    qDebug() << "Could not start server";
}
else
{
    qDebug() << "Listening to port " << port ;
  }

  }
   void myserver::incomingconnection(int socketDescriptor)
  {
  connect(&s_server, SIGNAL(newConnection()),
  this, SLOT(acceptConnection()));

s_server.listen(QHostAddress::Any, 1234);

qDebug() << socketDescriptor << " Connecting...";

mythread *thread = new mythread(socketDescriptor,this);

connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));

thread->start();

 }

如果你帮助我,我将不胜感激。

1 个答案:

答案 0 :(得分:1)

你没有很好地使用QThread。你可以使用SIGNAL和SLOTS,以及MoveToThread()函数。谷歌吧。

当你使用QThread时,Run()函数中的代码将在另一个线程中运行。 acceptConnection将在主线程中运行。

还搜索nextPendingConnection();

void myserver::incomingconnection(int socketDescriptor)
{
connect(&s_server, SIGNAL(newConnection()),this, SLOT(acceptConnection()));
...

不行。这个连接应该被调用一次(也许是构造函数)。不是为了任何接触。