2017-01-11 16 views
0

Qtでサーバを作成しようとしています。場合によっては正常に動作しますが、最初のクライアントが接続しようとするとクラッシュすることがあります。 私は共通のQTcpServerとQTcpSocketから継承したMySocketを使用します。クライアント接続時にQTサーバがクラッシュすることがある

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; 
}; 

スタートdefenition

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 ;.それがプログラマーであればクラッシュしますが、そうでなければクラッシュしません。私が間違っていることは何ですか?

+0

'server-> nextPendingConnection()'から 'QTcpSocket *'を自分の 'MySocket *'クラスにキャストできたらどうなるでしょうか? – E4z9

+0

うーん、私は相続人がそれを行うことができると思った。私がしようとするとMySocketのコンストラクタが欠けていますか? – luden

答えて

2

QTcpServerのデフォルトの実装では、新しい接続が到着したときにQTcpSocketの新しいインスタンスが作成されます。これはserver->nextPendingConnection()を呼び出すときのものです。このインスタンスを独自のMySocketにキャストすると、実行時に(予想外の拡張に)失敗します。

独自のQTcpSocketサブクラスを使用するには、あなたは、QTcpServerサブクラスでincomingConnection(qintptr socketDescriptor)を再実装独自のソケットクラスのインスタンスを作成し、addPendingConnectionと保留中の接続に追加する必要があります。

サイドノート:You should avoid using C-style cast (MySocket *)、それは危険です。キャストが成功することがわかっている場合はstatic_cast、そうでない場合はdynamic_castを使用してください(結果を確認してください)。

関連する問題