【问题标题】:QT server sometimes crashes, when client connecting客户端连接时,QT 服务器有时会崩溃
【发布时间】: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-&gt;nextPendingConnection() 获得的QTcpSocket * 转换为您自己的MySocket * 类?
  • 嗯,我认为继承人可以做到这一点。当我尝试这样做时,我想念 MySocket 构造函数?

标签: c++ qt


【解决方案1】:

QTcpServer 的默认实现会在新连接进入时创建QTcpSocket 的新实例,这就是调用server-&gt;nextPendingConnection() 时得到的结果。将此实例转换为您自己的 MySocket 将在运行时失败(扩展至不可预测的范围)。

要使用您自己的QTcpSocket 子类,您需要在QTcpServer 子类中重新实现incomingConnection(qintptr socketDescriptor),创建您自己的套接字类的实例,并将其添加到带有addPendingConnection 的挂起连接中。

旁注:You should avoid using C-style cast (MySocket *),这是不安全的。如果您确定演员表会成功,请使用static_cast,否则请使用dynamic_cast(然后检查结果)。

【讨论】:

    猜你喜欢
    • 2023-03-04
    • 1970-01-01
    • 2021-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多