Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Cannot disconnect server child client



  • In my Window Qt application, I've created a server and assigned it to listen to a particular ip address/port. I am able to make connection with a client and communicate with it. However, an issue I seem to be running into is that when my application closes, I am unsuccessfully disconnecting my client socket, causing my server to close unsuccessfully. This then causes my application to unsuccessfully connect to the client the next time my application starts. I will have to reboot the pc to get the port to reset. My current code is as follow:

    @
    // Server code
    Server::Server(QObject *parent)
    : QTcpServer(parent)
    {
    client = NULL;
    connect(this, SIGNAL(newConnection()), this, SLOT(handleNewConnection()));
    }
    Server::~Server()
    {
    }

    void Server::handleNewConnection()
    {
    client = nextPendingConnection();
    connect(client, SIGNAL(readyRead()), this, SLOT(onSocketReadyRead()));
    }
    void Server::onSocketReadyRead()
    {
    char buffer[1024] = {0};
    client->read(buffer, client->bytesAvailable());
    emit DisplayString(this, QString(&buffer[0]));
    }
    void Server::SendCommand(QString str)
    {
    if (client != NULL)
    {
    int n = client->write(str.toUtf8());
    qDebug() << "length: " << n << "string: " << str;
    }
    }
    void Server::DisconnectClient()
    {
    if (client != NULL && client->isOpen())
    {
    client->disconnectFromHost();
    client->deleteLater();
    client = NULL;
    }
    }

    // instantiating server from main
    server[0] = new Server();
    server[0].listen(QHostAddress::LocalHost, 5000);

    // disconnecting routine in main
    server[0].DisconnectClient();
    server[0].close();

    @

    Can someone tell me how I can disconnect my client socket from my server properly? I am using command line "netstat" to view my port status and the code above does not seem to destroy my client socket. Thanks!


Log in to reply