2016-05-14 35 views
0

QTcpServerはここにあります(QtのFortune Serverの例の簡略版)。以前はうまくいきました。それから私はいくつかのことを移動し、いくつかのコードを変更しました。今、私のサーバーは起動時にクラッシュします。私の知る限り、QTcpServer :: nextPendingConnection()の後にQTcpSocketがNULLになる

tcpSocket = tcpServer->nextPendingConnection(); 

後tcpSocketはNULLまま。したがって、tcpSocket-> anyCall()のようなすべてのコールは、segフォルトを引き起こします。アプリケーションの出力を示し:

QObject::connect: invalid null parameter 

私は移動する前に、その周りに物事がうまく働いていたとき、私の質問は、なぜtcpServer-> nextPendingConnection()、 突然のすべてをNULLを返しているのですか?あなたが接続をincomming必要nextPendingConnection使用するには

#include <QtWidgets> 
#include <QtNetwork> 
#include "server.h" 

Server::Server(QWidget *parent) 
: QDialog(parent), statusLabel(new QLabel), tcpServer(Q_NULLPTR), tcpSocket(Q_NULLPTR), networkSession(0), blockSize(0), userAuthenticated(false) 
{ 
    QNetworkConfigurationManager manager; 
    QNetworkConfiguration config = manager.defaultConfiguration(); 
    networkSession = new QNetworkSession(config, this); 
    sessionOpened(); 

    ... 
    // GUI stuff here // 
    ... 

    this->read_newClient(); 
} 

void Server::sessionOpened() 
{ 
    tcpServer = new QTcpServer(this); 

    // some if else checks here // 

    tcpSocket = tcpServer->nextPendingConnection(); // problem here // 
    connect(tcpSocket, &QAbstractSocket::disconnected, tcpSocket, &QObject::deleteLater); // line that crashes // 
} 

void Server::read_newClient() 
{ 
    QString data; 
    if (!clientSocket->waitForReadyRead()) 
    { 
     qDebug() << "Cannot read"; 
     return; 
    } 
    data = readData(); 
} 

答えて

3

:ここ

は、私のコードの関連部分です。したがって、あなたは二つの方法があります。

  1. 接続newConnectionと()シグナルを送る:呼び出しを忘れてはいけない

    if (tcpServer->waitForNewConnection()) { 
        if (tcpServer->hasPendingConnections()) { 
         tcpSocket = tcpServer->nextPendingConnection(); 
         connect(tcpSocket, &QAbstractSocket::disconnected, tcpSocket, QObject::deleteLater); 
        } 
    } 
    

... 
connect(tcpServer, &QTcpServer::newConnection, this, &Server::OnNewConnection); 
... 
void Server::OnNewConnection() { 
    if (tcpServer->hasPendingConnections()) { 
     tcpSocket = tcpServer->nextPendingConnection(); 
     connect(tcpSocket, &QAbstractSocket::disconnected, tcpSocket, QObject::deleteLater); 
    } 
} 
  • またはCALL waitForNewConnectionを()ブロックを使用しますtcpServer->listen();

  • +0

    ありがとうございますあなたの答え。 Btw私はあなたの接続呼び出しの最後の引数を理解していませんでした。また、私はnetworkSession-> open()を見逃していました。 – DDauS

    +0

    @Deedaus Edited –

    +0

    @Deedaus QTcpServerはnetworkSessionとは独立して動作できます。 –

    関連する問題