QTcpServer listen successfully,but without emiting newConnection

  • Hi , I test QTcpServer of Qt5.3.1. The steps are following:

    m_pTCPServer = new QTcpServer(this);
    if(m_pTCPServer->listen(QHostAddress::Any, m_localPort))
    ret = true;

    I can test the listening is OK with a tcp client connection, but the slot 'server_New_Connect' never be emitted.

    Anyone has already encounted this problem,pls give me some advice,thanks a lot.

  • @pinkie said in QTcpServer listen successfully,but without emiting newConnection:


    Can you check the return value of connect? the easiest way is to wrap it into Q_ASSUME: Q_ASSUME(QObject::connect(m_pTCPServer,SIGNAL(newConnection()),this,SLOT(server_New_Connect())));

  • @pinkie said in QTcpServer listen successfully,but without emiting newConnection:

    I can test the listening is OK with a tcp client connection

    By this, do you mean that your client does a connectToHost() and a connected() signal is subsequently emitted by the client?

    Have you looked a the Fortune client/server examples?

  • @pinkie I lack context of where you're creating your QTcpServer object but the following code is working fine for me (Qt 5.9.0): basic Qt Widgets Application project with m_pTCPServer member added to MainWindow class :


    #ifndef MAINWINDOW_H
    #define MAINWINDOW_H
    #include <QMainWindow>
    #include <QtNetwork/QTcpServer>
    namespace Ui {
    class MainWindow;
    class MainWindow : public QMainWindow
        explicit MainWindow(QWidget *parent = 0);
    public slots:
        void server_New_Connect();
        Ui::MainWindow *ui;
        QTcpServer* m_pTCPServer;
    #endif // MAINWINDOW_H


    #include "mainwindow.h"
    #include "ui_mainwindow.h"
    #include <QDebug>
    MainWindow::MainWindow(QWidget *parent) :
        ui(new Ui::MainWindow)
        m_pTCPServer = new QTcpServer(this);
        QObject::connect(m_pTCPServer, SIGNAL(newConnection()), this, SLOT(server_New_Connect()));
        if (m_pTCPServer->listen(QHostAddress::Any, 9999))
            qDebug() << "Server up and listening!";
        delete ui;
    void MainWindow::server_New_Connect()
        qDebug() << "New connection!";

    program output when using command telnet localhost 9999

    Server up and listening!
    New connection!

  • Thanks all for your help. I find the point. The new QTcpServer... code is within run function of my thread. It works well if I move it outside. I should learn more about QTcpServer and QThread. Thank you.

  • @pinkie
    Mark this post a solved.

  • @pinkie you may want to take a look at threaded fortune server example. And as @Taz742 mentioned, please don't forget to mark the post as solved.

  • What happend when connection server&client is always open?

Log in to reply

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.