gpt4 book ai didi

c++ - 客户端连接时,QT 服务器有时会崩溃

转载 作者:行者123 更新时间:2023-11-30 02:27:30 24 4
gpt4 key购买 nike

我正在尝试在 Qt 上创建服务器。有时效果很好,但有时会在第一个客户端尝试连接时崩溃。我使用普通的 QTcpServer 和从 QTcpSocket 继承的 MySocket。

    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;。如果它在程序中,它会崩溃,但如果没有 - 程序不会崩溃。我做错了什么?

最佳答案

QTcpServer 的默认实现会在新连接进入时创建一个新的 QTcpSocket 实例,这就是调用 server->nextPendingConnection 时得到的结果()。将此实例转换为您自己的 MySocket 将在运行时失败(达到不可预测的程度)。

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

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

关于c++ - 客户端连接时,QT 服务器有时会崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41590708/

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