【发布时间】:2017-01-11 20:48:30
【问题描述】:
我正在尝试在 Qt 上制作服务器。有时它运行良好,但有时当第一个客户端尝试连接时它会崩溃。 我使用普通的 QTcpServer 和我的 MySocket 继承自 QTcpSocket。
class MySocket : public QTcpSocket
{
public:
CShip *parentShip;
int pt_type;
int descriptor;
QListView *log;
QStandardItemModel *log_model;
public:
MySocket();
qint64 MyWrite(char* data, quint64 maxSize);
void LogAddString(QString str);
};
我有一个全局日志(QListView)和一个 log_model(QStandardItemModel)。哪个用途,嗯,就像日志一样。每个套接字都必须有指向两者的指针。
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
void LogAddString(QString str);
private slots:
void newUser();
void slotReadClient();
void UserCreate();
void DataUpdate();
void UserDisconnected();
private:
Ui::MainWindow *ui;
QTcpServer *server;
QMap<int, MySocket*> SClients;
MyTableModel *table_model;
QStandardItemModel *log_model;
QTimer *timer_update;
};
开始防御
log_model = new QStandardItemModel();
ui->log->setModel(log_model);
server = new QTcpServer(this);
connect(server, SIGNAL(newConnection()), this, SLOT(newUser()));
server->listen(QHostAddress::Any, 63258);
和崩溃的时刻 -
void MainWindow::newUser()
{
MySocket* clientSocket;
clientSocket = (MySocket*)(server->nextPendingConnection());
clientSocket->log = ui->log;
clientSocket->log_model = log_model;
/*clientSocket->pt_type = 0;
int idusersocs = clientSocket->socketDescriptor();
SClients[idusersocs] = clientSocket;
clientSocket->descriptor = idusersocs;
connect(clientSocket, SIGNAL(readyRead()), this, SLOT(slotReadClient()));
connect(clientSocket, SIGNAL(disconnected()), this, SLOT(UserDisconnected()));*/
}
评论前的最后一个字符串-clientSocket->log_model = log_model;。如果它在程序中,它会崩溃,但如果不是 - 程序不会崩溃。我做错了什么?
【问题讨论】:
-
是什么让您期望能够将从
server->nextPendingConnection()获得的QTcpSocket *转换为您自己的MySocket *类? -
嗯,我认为继承人可以做到这一点。当我尝试这样做时,我想念 MySocket 构造函数?