我在Qt编写简单的客户端服务器程序,服务器是多线程的。 对于一台服务器,它可以正常工作,它可以从客户端向服务器发送消息,但是以多线程形式它不起作用,它连接到线程并且还显示消息"客户端连接"但它无法显示客户端发送的消息! 我搜索了很多芽,我无法找到问题所在,以及任何解决方案。这是我的代码: 请你帮助我好吗。提前谢谢。
myserver.cpp
#include "myserver.h"
#include "mythread.h"
myserver::myserver(QObject * parent): QTcpServer(parent)
{
}
void myserver::startserver()
{
int port = 6666;
if (!this - > listen(QHostAddress::Any, port)) {
qDebug() << "Could not start server ";
} else {
qDebug() << "Listening to port ";
}
}
void myserver::incomingConnection(qintptr socketDescriptor)
{
qDebug() << socketDescriptor << " Connecting...";
mythread * thread = new mythread(socketDescriptor, this);
connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));
thread - > start();
}
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";
socket = new QTcpSocket();
if(!socket->setSocketDescriptor(this->socketDescriptor)) {
emit error(socket->error());
return;
}
connect(socket, SIGNAL(readyRead()), this, SLOT(readSocket()));
qDebug() << socketDescriptor << " Client connected";
}
void mythread::readSocket()
{
QByteArray Data = socket->readAll();
qDebug()<< socketDescriptor <<" Data in: " << Data;
socket->write(Data);
}
答案 0 :(得分:2)