gpt4 book ai didi

c++ - 多线程服务器

转载 作者:行者123 更新时间:2023-11-28 05:56:18 25 4
gpt4 key购买 nike

我正在编写多线程服务器,但我在接受连接和启动读取功能时遇到问题。我不知道我应该把它们写在哪里..这是我的代码:“我的线程.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);
}

“我的服务器.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();

}

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

最佳答案

您没有很好地使用 QThread。您可以使用 SIGNAL 和 SLOTS 以及 MoveToThread() 函数。谷歌一下。

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

同时搜索 nextPendingConnection();

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

不行。这个连接应该被调用一次(也许是构造函数)。不适用于任何传入连接。

关于c++ - 多线程服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34105221/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com