我有一项任务是创建一个支持网络游戏的国际象棋游戏。 为了开发,我一直在使用Qt。 问题如下: 我有“MyServer”课程: 标题文件 - >
//Header file "MyServer.h"
#ifndef MYSERVER_H
#define MYSERVER_H
#include <QTcpServer>
#include <QTcpSocket>
#include <mythread.h>
#include <QDebug>
class MyServer : public QTcpServer
{
Q_OBJECT
public:
explicit MyServer(QObject *parent = 0);
void startServer();
QList<QString> *usersOnline;
QList<QTcpSocket*> *connections;
signals:
public slots:
protected:
void incomingConnection(int socketDescriptor);
private:
QTcpServer* server;
//QTcpSocket* socket;
//QByteArray* bytes;
//QString* str;
};
#endif // MYSERVER_H
cpp.file
#include "myserver.h"
MyServer::MyServer(QObject *parent) :
QTcpServer(parent)
{
}
void MyServer::startServer()
{
this->listen(QHostAddress::Any,1234);
usersOnline=new QList<QString>;
}
void MyServer::incomingConnection(int socketDescriptor)
{
MyThread* thread=new MyThread(socketDescriptor,this,this);
thread->run();
}
如您所见,具有新连接的此类创建了一个新线程。 “MyThread”类。 头文件
#ifndef MYTHREAD_H
#define MYTHREAD_H
#include <QThread>
#include <QTcpSocket>
#include <QTcpServer>
#include <QDebug>
#include <QDataStream>
#include <QObject>
#include <myserver.h>
class MyServer;
class MyThread : public QThread
{
Q_OBJECT
public:
explicit MyThread(int ID,MyServer* s,QObject *parent = 0);
void run();
signals:
public slots:
void readyRead();
private:
QTcpSocket* socket;
int socketDescriptor;
};
#endif // MYTHREAD_H
cpp.file
#include "mythread.h"
MyThread::MyThread(int ID,MyServer* s,QObject *parent) :
QThread(parent)
{
//this->mainserver=parent;
//parent=new MyServer();
//qDebug()<<s->usersOnline;
this->socketDescriptor=ID;
}
void MyThread::run()
{
qDebug()<<"Starts thread";
socket=new QTcpSocket();
socket->setSocketDescriptor(this->socketDescriptor);
connect(socket,SIGNAL(readyRead()),this,SLOT(readyRead()),Qt::DirectConnection);
exec();
}
void MyThread::readyRead()
{
QDataStream in(this->socket);
quint32 n;
in>>n;
qDebug()<<n;
QByteArray bytes;
QDataStream out(&bytes,QIODevice::WriteOnly);;
QString str;
switch (n) {
case 1:
in>>str;
qDebug()<<str;
//usersOnline->append(str);
//qDebug()<<*(usersOnline);
//out(&bytes,QIODevice::WriteOnly);
//out<<(*usersOnline);
//for(int i=0;i<this->connections->length();i++)
//{
//connections->at(i)->is
//connections->at(i)->write(bytes);
//connections->at(i)->waitForBytesWritten(2000);
// }
break;
case 2:
in>>str;
qDebug()<<str;
break;
}
}
在“MyThread”构造函数中,我将指针传递给“MyServer”类,以使用字段“usersOnline”,“connections”和“MyServer”方法。
因此,我在我的架构“循环依赖”中使用“MyServer”和“MyThread”类。 如何改变架构? 非常感谢。
答案 0 :(得分:0)
从您的帖子标题中删除#include <myserver.h>
。你已经有了class MyServer;
前向定义,这就足够了。